10/28
Part 3 of 7 · GreedyLearn and do

Greedy takes the biggest coin, and that can fail

Greedy never takes a coin back

The cashier's method takes the biggest coin that fits, then repeats. That's greedy. Here it is next to the table:

def greedy(amount: float, coins: list[float]) -> int:
    """Biggest coin first, never taken back. The coin count, or -1."""
    left, used = round(amount * 100), 0
    for v in sorted({round(c * 100) for c in coins}, reverse=True):
        used += left // v
        left %= v
    return used if left == 0 else -1

for amount, coins in [(0.06, [0.01, 0.03, 0.04]),
                      (0.30, [0.10, 0.25]),
                      (0.30, [0.01, 0.10, 0.25])]:
    print(greedy(amount, coins), min_coins(amount, coins))
Predict

Greedy against the table, for 6 cents from coins of 1, 3 and 4?

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