Skip to content

Commit 8b092d9

Browse files
committed
Improve making change caching
1 parent 8905e62 commit 8b092d9

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,24 @@ 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 to store computed results
11+
cache = {}
12+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache)
1113

1214

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
15+
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
1416
"""
1517
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1618
"""
1719
if total == 0 or len(coins) == 0:
1820
return 0
1921

22+
# Create cache key from current state
23+
cache_key = (total, tuple(coins))
24+
25+
if cache_key in cache:
26+
return cache[cache_key]
27+
2028
ways = 0
2129
for coin_index in range(len(coins)):
2230
coin = coins[coin_index]
@@ -26,7 +34,10 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2634
if total_from_coins == total:
2735
ways += 1
2836
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
37+
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:], cache=cache)
3038
ways += intermediate
3139
count_of_coin += 1
40+
41+
# Store result in cache
42+
cache[cache_key] = ways
3243
return ways

0 commit comments

Comments
 (0)