Skip to content

Commit 32b442b

Browse files
committed
Optimize making_change: add cache and math check for better performance
1 parent 9b61b96 commit 32b442b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,38 @@
11
from typing import List
22

3+
cache = {}
34

45
def ways_to_make_change(total: int) -> int:
56
"""
67
Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200, returns a count of all of the ways to make the passed total value.
78
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
"""
11+
# Clear cache before starting new calculation
12+
cache.clear()
1013
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
1114

1215

1316
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
1417
"""
1518
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1619
"""
20+
# We use tuple(coins) because lists cannot be keys.
21+
key = (total, tuple(coins))
22+
23+
if key in cache:
24+
return cache[key]
25+
1726
if total == 0 or len(coins) == 0:
1827
return 0
1928

29+
# Check if only one coin type remains
30+
if len(coins) == 1:
31+
if total % coins[0] == 0:
32+
return 1
33+
else:
34+
return 0
35+
2036
ways = 0
2137
for coin_index in range(len(coins)):
2238
coin = coins[coin_index]
@@ -29,4 +45,7 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2945
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
3046
ways += intermediate
3147
count_of_coin += 1
48+
49+
# Store result in cache
50+
cache[key] = ways
3251
return ways

0 commit comments

Comments
 (0)