13/28
Part 4 of 7 · Count the waysLearn and do

Count the ways with the coin loop outside

Order ignored is a combination, order counted is an ordering

Here are all the ways to make 6 cents from coins of 1, 3 and 4:

A combination, order ignoredIts orderings, order countedHow many
1+1+1+1+1+11+1+1+1+1+11
3+1+1+13+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+34
3+33+31
4+1+14+1+1, 1+4+1, 1+1+43
4 combinations9 orderings9

The problem asks for combinations. The order of your two loops decides which one you count. Here is the version with the coins outside:

def count_ways(amount: float, coins: list[float]) -> int:
    """Combinations that make amount exactly, order ignored."""
    target = round(amount * 100)
    values = sorted({round(c * 100) for c in coins})
    # one way to make 0: no coins
    ways = [1] + [0] * target
    # coins outside
    for v in values:
        # amounts inside
        for t in range(v, target + 1):
            ways[t] += ways[t - v]
    return ways[target]

print(count_ways(0.06, [0.01, 0.03, 0.04]))
4

ways[t] is the number of ways to make t cents. Each coin makes one pass over the amounts, from its own value up, and adds ways[t - v] to ways[t]. That counts the 4 combinations. Swap the two loops, with the amounts outside and every coin that fits inside, and the same addition counts the 9 orderings.

The table is the same shape as for the fewest coins. Only the rules change:

Fewest coinsNumber of ways
a cell holdsthe fewest coins that make tthow many combinations make tt
startbest[0] = 0, every other cell ∞\inftyways[0] = 1, every other cell 0
combinethe min over coins, plus 1the sum over coins
loop ordereither onecoins outside
unreachable-10

ways[0] = 1 is not a hack. There is exactly one way to make 0 cents: take no coins. Every count is built on it, because a coin worth exactly tt adds ways[0] to ways[t]. Start it at 0 and every count stays 0. It's also why count_ways(0.0, [0.25]) is 1.

In the editor, write orderings(target, values), in cents: how many sequences of coins make target, with order counted. Put the amount loop outside, and the coins that fit inside it.