Skip to content

Commit 62e1e71

Browse files
committed
making_change
1 parent 2da2744 commit 62e1e71

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from typing import List
22

3+
cache = {}
34

45
def ways_to_make_change(total: int) -> int:
56
"""
@@ -8,14 +9,25 @@ def ways_to_make_change(total: int) -> int:
89
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.
910
"""
1011
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
12+
1113

1214

1315
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
16+
key = (total, tuple(coins))
17+
if key in cache:
18+
return cache[key]
1419
"""
1520
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1621
"""
1722
if total == 0 or len(coins) == 0:
18-
return 0
23+
result = 0
24+
cache[key] = result
25+
return result
26+
27+
if total == 1 or len(coins) == 1:
28+
result = 1
29+
cache[key] = result
30+
return result
1931

2032
ways = 0
2133
for coin_index in range(len(coins)):
@@ -29,4 +41,6 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2941
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
3042
ways += intermediate
3143
count_of_coin += 1
32-
return ways
44+
45+
cache[key] = ways
46+
return ways

0 commit comments

Comments
 (0)