22/28
Part 6 of 7 · A worked exampleLearn and do

A worked example: 30 cents from dimes and quarters

The practice problem's first test asks for min_coins(0.30, [0.10, 0.25]). Here is the whole path, with what to say at each step.

1. Name the trap. These are floats, so convert to cents with round, once. That gives 30 cents and coins of 10 and 25. Their GCD is 5, and 5 divides 30, so an answer may exist.

2. Fill the table. One cell per cent, from 0 to 30:

target = round(0.30 * 100)
values = [round(c * 100) for c in [0.10, 0.25]]
best = [0] + [math.inf] * target
for t in range(1, target + 1):
    for v in values:
        if v <= t and best[t - v] + 1 < best[t]:
            best[t] = best[t - v] + 1
print(target, values)
print({t: best[t] for t in range(target + 1) if best[t] != math.inf})
Predict

Coins of 10 and 25. Which amounts up to 30 cents can be made?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

The third line asks for an amount of 0 from quarters. How many coins, and how many ways?

Pick one to see what it prints.
Pick an answer above to see the rest