-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathmaking_change.py
More file actions
51 lines (42 loc) · 1.78 KB
/
making_change.py
File metadata and controls
51 lines (42 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from typing import List
# Cache dictionary to store computed results
# Key: (total, tuple(coins)) -> Value: number of ways
change_cache = {}
def ways_to_make_change(total: int) -> int:
"""
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.
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.
"""
# Clear cache for each new call to avoid interference between tests
change_cache.clear()
coins = [200, 100, 50, 20, 10, 5, 2, 1]
return ways_to_make_change_helper(total, coins)
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
"""
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
"""
# Create a cache key - use tuple of coins since lists are not hashable
cache_key = (total, tuple(coins))
# Check if we already computed this combination
if cache_key in change_cache:
return change_cache[cache_key]
# Base cases
if total == 0:
return 1 # One way to make 0: use no coins
if len(coins) == 0:
return 0 # No coins left but still need to make total > 0
ways = 0
for coin_index in range(len(coins)):
coin = coins[coin_index]
count_of_coin = 1
while coin * count_of_coin <= total:
total_from_coins = coin * count_of_coin
if total_from_coins == total:
ways += 1
else:
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
ways += intermediate
count_of_coin += 1
# Store result in cache before returning
change_cache[cache_key] = ways
return ways