Skip to content

Commit 7c6c632

Browse files
authored
Update 2 making_change.py
1 parent 527cba8 commit 7c6c632

File tree

1 file changed

+35
-23
lines changed

1 file changed

+35
-23
lines changed
Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,57 @@
1-
from typing import List
2-
cache = {}
3-
def ways_to_make_change(total: int) -> int:
4-
"""
5-
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.
61

7-
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.
8-
"""
9-
2+
from typing import List, Dict, Tuple
3+
4+
# Pre-create only 8 possible "coins" arrays
5+
_BASE_COINS: List[int] = [200, 100, 50, 20, 10, 5, 2, 1]
6+
COIN_SUFFIXES: List[Tuple[int, ...]] = [tuple(_BASE_COINS[i:]) for i in range(len(_BASE_COINS))]
7+
8+
cache: Dict[Tuple[int, int], int] = {}
9+
10+
def ways_to_make_change(total: int) -> int:
1011
cache.clear()
11-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
12+
# suffix_id == 0 identifies [200, 100, 50, 20, 10, 5, 2, 1]
13+
return ways_to_make_change_helper(total, suffix_id=0)
1214

1315

14-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
16+
def ways_to_make_change_helper(total: int, suffix_id: int) -> int:
1517
"""
16-
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
18+
suffix_id uniquely identifies the subarray coins = COIN_SUFFIXES[suffix_id]
19+
where suffix_id in [0..7].
1720
"""
18-
key = (total, tuple(coins))
19-
21+
key = (total, suffix_id)
2022
if key in cache:
2123
return cache[key]
22-
23-
if total == 0 or len(coins) == 0:
24+
25+
coins = COIN_SUFFIXES[suffix_id]
26+
27+
# Keep behavior close to original, but fix the standard base case:
28+
if total == 0:
29+
return 1
30+
if len(coins) == 0:
2431
return 0
25-
32+
2633
if len(coins) == 1:
27-
if total % coins[0] == 0:
28-
return 1
29-
else:
30-
return 0
31-
34+
cache[key] = 1 if (total % coins[0] == 0) else 0
35+
return cache[key]
36+
3237
ways = 0
3338
for coin_index in range(len(coins)):
3439
coin = coins[coin_index]
3540
count_of_coin = 1
41+
3642
while coin * count_of_coin <= total:
3743
total_from_coins = coin * count_of_coin
44+
3845
if total_from_coins == total:
3946
ways += 1
4047
else:
41-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
42-
ways += intermediate
48+
# Instead of slicing coins[coin_index+1:], move the suffix_id forward.
49+
# suffix_id is the start index of `coins` in the base list, so:
50+
next_suffix_id = suffix_id + coin_index + 1
51+
if next_suffix_id < len(COIN_SUFFIXES):
52+
ways += ways_to_make_change_helper(total - total_from_coins, suffix_id=next_suffix_id)
53+
4354
count_of_coin += 1
55+
4456
cache[key] = ways
4557
return ways

0 commit comments

Comments
 (0)