Skip to content

Commit 6d1855e

Browse files
committed
Implement memoisation + fix incorrect base case
1 parent 3a65803 commit 6d1855e

1 file changed

Lines changed: 19 additions & 3 deletions

File tree

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from typing import List
2-
2+
cache = {}
33

44
def ways_to_make_change(total: int) -> int:
55
"""
@@ -11,22 +11,38 @@ def ways_to_make_change(total: int) -> int:
1111

1212

1313
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
1415
"""
1516
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1617
"""
17-
if total == 0 or len(coins) == 0:
18+
#We found one valid way if its an exact match.
19+
if total == 0:
20+
return 1
21+
#base case no coins left but still have remaining total but no way to form it
22+
if not coins:
1823
return 0
24+
#creating a cache key from our current prob, converting list to a tuple to make it hashable
25+
key = (total, tuple(coins))
26+
if key in cache:
27+
return cache[key]
28+
1929

2030
ways = 0
31+
# Try using the current coin 1,2,3...times as long as we don't exceed the total.
2132
for coin_index in range(len(coins)):
2233
coin = coins[coin_index]
2334
count_of_coin = 1
2435
while coin * count_of_coin <= total:
2536
total_from_coins = coin * count_of_coin
26-
if total_from_coins == total:
37+
if total_from_coins == total: #if we get an exact match ++ on ways
2738
ways += 1
39+
40+
#remaining total and remaining coins after using the current one
2841
else:
2942
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
3043
ways += intermediate
44+
3145
count_of_coin += 1
46+
cache[key] = ways
3247
return ways
48+

0 commit comments

Comments
 (0)