The problem
You have as many coins as you like of each value in coins (all different, all at least 1). Return the number of different ways to pay exactly amount. Only how many coins of each value you use matters, not their order: 1 + 2 and 2 + 1 are the same way.
ways_to_pay(5, [1, 2, 5]) # 4
# 5, 2+2+1, 2+1+1+1, 1+1+1+1+1
ways_to_pay(4, [1, 2, 3]) # 4, not 7
ways_to_pay(0, [7]) # 1: pay with nothing
Limits
amountis up to 100,000 and there are up to 30 coin values. The counts can be very large; Python’s whole numbers hold them exactly.- Python stops at about 1,000 nested calls, and a function wrapped in
functools.cachestops after a few hundred in the browser. The big tests need far more than that, so memoised recursion fails them. Fill a table with a loop (lesson 3).
Builds on DYNP-8 The knapsack family.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
9 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Order does not matter | Not run | |
| 3 | Cannot be paid | Not run | |
| 4 | Amount 0 | Not run | |
| 5 | One coin, exactly | Not run | |
| 6 | Coins in any order | Not run | |
| 7 | A dollar in cents | Not run | |
| 8 | ₹100,000 in Indian coins and notes | Not run | |
| 9 | 50,000 with 30 odd coins | Not run |