18/28
Part 5 of 7 · What it costsLearn and do
Top-down is the same formula, as a recursive function with a cache
Everything so far is bottom-up: a list filled from 0 to the target. The other way is top-down: the formula as a recursive function, with a cache so each amount is solved once.
import math
from functools import cache
def min_coins_top_down(amount: float, coins: list[float]) -> int:
"""min_coins as a recursive function with a cache."""
values = sorted({round(c * 100) for c in coins}, reverse=True)
@cache
def best(t: int) -> float:
"""The fewest coins for t cents, or math.inf."""
if t == 0:
return 0
return min((best(t - v) + 1 for v in values if v <= t),
default=math.inf)
answer = best(round(amount * 100))
return -1 if answer == math.inf else answer
print(min_coins_top_down(0.06, [0.01, 0.03, 0.04]))
print(min_coins_top_down(500.00, [0.01, 0.05, 0.10, 0.25, 1.00, 5.00]))
2
100
Both versions keep the same answers. They keep them in different places:
| For 6 cents from 1, 3 and 4 | What it holds |
|---|---|
| bottom-up: a list, filled from 0 up | [0, 1, 2, 1, 1, 2, 2] at indexes 0 to 6 |
| top-down: a dict inside the cache, filled as each call comes back | {0: 0, 1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 2} |
Read the min call inside out:
- For each coin
vthat fits,best(t - v) + 1is the fewest coins fortwithvas the last coin. - The inner parentheses make a generator of those counts, and
mintakes the smallest. default=math.infis whatminreturns when no coin fits, so an unreachable amount comes back asmath.inf.
@cache is just the shortest way to get that dict. A plain dict you fill yourself does the same job.
It's the formula almost word for word. That makes it the quickest way to get a correct answer on the board.
@cache hides the dict it keeps. In the editor, write best(t) inside fewest_memo(target, values) with the dict itself: look an amount up in memo before you work it out, and store it after. It prints the same three answers as the table.