Skip to content

Commit c98d800

Browse files
committed
refactor ways_to_make_change function to improve caching
1 parent bcc9ee4 commit c98d800

File tree

2 files changed

+20
-35
lines changed

2 files changed

+20
-35
lines changed
Lines changed: 18 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,25 @@
1-
from typing import List
2-
3-
41
def ways_to_make_change(total: int) -> int:
5-
"""
6-
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.
2+
cache = {}
3+
coins = (200, 100, 50, 20, 10, 5, 2, 1)
74

8-
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.
9-
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
5+
def helper(remaining: int, start: int) -> int:
6+
if remaining == 0:
7+
return 1
8+
if remaining < 0 or start == len(coins):
9+
return 0
1110

11+
key = (remaining, start)
12+
if key in cache:
13+
return cache[key]
1214

13-
cache = {}
15+
coin = coins[start]
16+
ways = 0
1417

18+
max_count = remaining // coin
19+
for count in range(max_count + 1):
20+
ways += helper(remaining - count * coin, start + 1)
1521

16-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
17-
"""
18-
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
19-
"""
20-
if total == 0 or len(coins) == 0:
21-
return 0
22+
cache[key] = ways
23+
return ways
2224

23-
ways = 0
24-
for coin_index in range(len(coins)):
25-
coin = coins[coin_index]
26-
count_of_coin = 1
27-
while coin * count_of_coin <= total:
28-
total_from_coins = coin * count_of_coin
29-
if total_from_coins == total:
30-
ways += 1
31-
else:
32-
key = (total - total_from_coins, tuple(coins[coin_index + 1 :]))
33-
if key not in cache:
34-
cache[key] = ways_to_make_change_helper(
35-
total - total_from_coins, coins=coins[coin_index + 1 :]
36-
)
37-
intermediate = cache[key]
38-
else:
39-
intermediate = cache[key]
40-
ways += intermediate
41-
count_of_coin += 1
42-
return ways
25+
return helper(total, 0)

Sprint-2/improve_with_caches/making_change/making_change_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from making_change import ways_to_make_change
44

5+
56
class MakingChangeTest(unittest.TestCase):
67
def test_1(self):
78
# 1x 1p
@@ -27,5 +28,6 @@ def test_17(self):
2728
def test_9176(self):
2829
self.assertEqual(ways_to_make_change(9176), 628431158425225)
2930

31+
3032
if __name__ == "__main__":
3133
unittest.main()

0 commit comments

Comments
 (0)