11/28
Part 3 of 7 · GreedyLearn and do
You can check whether greedy is safe for a coin set
Compare greedy with the table on every amount below the sum of the two largest coins:
def first_greedy_miss(coins: list[float]) -> int | None:
"""The smallest amount in cents where greedy loses to the table, or None."""
two_largest = sorted(coins)[-2:]
for cents in range(1, round(sum(two_largest) * 100)):
amount = cents / 100
if greedy(amount, coins) != min_coins(amount, coins):
return cents
return None
print(first_greedy_miss([0.01, 0.05, 0.10, 0.25]))
print(first_greedy_miss([0.01, 0.03, 0.04]))
Where does greedy first lose to the table: for US coins, and for 1, 3 and 4?
Pick one to see what it prints.
Pick an answer above to see the rest
Why is it enough to check below the sum of the two largest coins?
Pick an answer above to see the rest