DYNP-P8

Ways to pay

Practice 8 of 9Dynamic programming9 tests

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

  • amount is 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.cache stops 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Order does not matterNot run
3Cannot be paidNot run
4Amount 0Not run
5One coin, exactlyNot run
6Coins in any orderNot run
7A dollar in centsNot run
8₹100,000 in Indian coins and notesNot run
950,000 with 30 odd coinsNot run