Skip to content

Commit eaca288

Browse files
committed
refactor: memoize ways to make change
1 parent 13ad347 commit eaca288

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

‎Sprint-2/improve_with_caches/making_change/making_change.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,17 @@ def ways_to_make_change(total: int) -> int:
77
88
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.
99
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
10+
cache = {}
11+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1],cache)
1112

1213

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
def ways_to_make_change_helper(total: int, coins: List[int],cache:dict[tuple,int]) -> int:
1415
"""
1516
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1617
"""
18+
key = (total,tuple(coins))
19+
if key in cache:
20+
return cache[key]
1721
if total == 0 or len(coins) == 0:
1822
return 0
1923

@@ -26,7 +30,9 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2630
if total_from_coins == total:
2731
ways += 1
2832
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
33+
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:],cache=cache)
3034
ways += intermediate
3135
count_of_coin += 1
36+
37+
cache[key]= ways
3238
return ways

0 commit comments

Comments
 (0)