-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmaking_change.py
More file actions
45 lines (37 loc) · 1.33 KB
/
making_change.py
File metadata and controls
45 lines (37 loc) · 1.33 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
from typing import List
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.
"""
cache = {}
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache)
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
"""
Helper function with memoization.
Cache key is (total, index of first coin in list) — but since we pass
the coins list by slicing, we can cache using tuple(total, tuple(coins)).
"""
key = (total, tuple(coins))
if key in cache:
return cache[key]
if total == 0 or len(coins) == 0:
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:],
cache=cache
)
ways += intermediate
count_of_coin += 1
cache[key] = ways
return ways