Skip to content

Commit 55157fa

Browse files
committed
Add manual caching to ways_to_make_change to speed up recursive calls
1 parent e93e7c9 commit 55157fa

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@ def ways_to_make_change(total: int) -> int:
1010
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
1111

1212

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
13+
def ways_to_make_change_helper(total: int, coins: List[int],cache=None) -> int:
1414
"""
1515
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1616
"""
1717
if total == 0 or len(coins) == 0:
1818
return 0
19-
19+
if cache is None:
20+
cache={}
21+
key=(total,tuple(coins))
22+
if key in cache:
23+
return cache[key]
24+
2025
ways = 0
2126
for coin_index in range(len(coins)):
2227
coin = coins[coin_index]
@@ -26,7 +31,8 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2631
if total_from_coins == total:
2732
ways += 1
2833
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
34+
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:],cache=cache)
3035
ways += intermediate
3136
count_of_coin += 1
37+
cache[key]=ways
3238
return ways

0 commit comments

Comments
 (0)