-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathmaking_change.py
More file actions
51 lines (41 loc) · 1.55 KB
/
making_change.py
File metadata and controls
51 lines (41 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from typing import List
cache = {}
def ways_to_make_change(total: int) -> int:
"""
Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200, returns a count of all of the ways to make the passed total value.
For instance, there are two ways to make a value of 3: with 3x 1 coins, or with 1x 1 coin and 1x 2 coin.
"""
# Clear cache before starting new calculation
cache.clear()
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
"""
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
"""
# We use tuple(coins) because lists cannot be keys.
key = (total, tuple(coins))
if key in cache:
return cache[key]
if total == 0 or len(coins) == 0:
return 0
# Check if only one coin type remains
if len(coins) == 1:
if total % coins[0] == 0:
return 1
else:
return 0
ways = 0
for coin_index in range(len(coins)):
coin = coins[coin_index]
count_of_coin = 1
while coin * count_of_coin <= total:
total_from_coins = coin * count_of_coin
if total_from_coins == total:
ways += 1
else:
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
ways += intermediate
count_of_coin += 1
# Store result in cache
cache[key] = ways
return ways