coins, ways = [1, 3, 4], [1] + [0] * 6print(f"{'no coins':<17}{ways}")for i, v in enumerate(coins): for t in range(v, 7): ways[t] += ways[t - v] print(f"{'coins ' + str(coins[:i + 1]):<17}{ways}")
Predict
After the 3-cent pass, what is ways[6]?
Pick one to see what it prints.
Each pass adds one row. Here is how the 3 at the end of the [1, 3] row is made:
Combinations, one coin pass at a timeInteractive
t0123456
coins 1
coins 1, 3
coins 1, 3, 4
Coins: 1, 3, 4. Tap a cell to see where its number comes from.
With coins up to 4: 3 ways with no 4, plus 1 with at least one 4: take it off and make 2. 3 + 1 = 4.
Each cell is the cell above it, plus the cell c columns to its left in the same row. A combination either has no coin c at all, and the row above already counted it, or it has at least one, and taking one off leaves a combination for t−c. As a formula:
Wi(t)=Wi−1(t)+Wi(t−ci)
Wi(t) counts the combinations that make t from the first i coins. Wi−1(t) is that count before coin ci arrived.
So every combination gets built in one fixed order: all the 1s, then the 3s, then the 4s. Each one is counted once.
The flat list holds one row at a time. When the inner loop reaches ways[t], it still holds the row above. ways[t - v] was already updated in this pass, so it's from the current row.
The set matters here too. With [0.05, 0.05] and no set, the nickel pass runs twice and finds 3 ways to make 10 cents instead of 1.
In the editor, write count_ways(target, values), in cents: how many combinations make exactly target, order ignored. Put the coins outside and the amounts inside, and count a coin listed twice only once.
Pick an answer above to see the rest
Instructions
1
Write count_ways(target, values), in cents: how many combinations of the coins make exactly target, order ignored. A coin listed twice is still one coin.