Skip to content

Commit 2a038aa

Browse files
committed
refactor: use memoisation to avoid recalulations
1 parent 77b822a commit 2a038aa

2 files changed

Lines changed: 25 additions & 24 deletions

File tree

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
_cache = {}
2-
3-
def fibonacci(n):
4-
if n in _cache:
5-
return _cache[n]
1+
def fibonacci(n, cache={}):
2+
if n in cache:
3+
return cache[n]
64

75
if n <= 1:
86
return n
97

108
result = fibonacci(n - 1) + fibonacci(n - 2)
11-
_cache[n] = result
9+
cache[n] = result
1210
return result
Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,35 @@
1-
from typing import List
2-
3-
41
def ways_to_make_change(total: int) -> int:
52
"""
63
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.
74
85
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.
96
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
7+
return ways_to_make_change_helper(total, 0)
118

129

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
10+
def ways_to_make_change_helper(total: int, coin_index: int, cache={}) -> int:
1411
"""
1512
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1613
"""
17-
if total == 0 or len(coins) == 0:
14+
coins = (200, 100, 50, 20, 10, 5, 2, 1)
15+
16+
key = (total, coin_index)
17+
18+
if key in cache:
19+
return cache[key]
20+
21+
if total == 0:
22+
return 1
23+
24+
if coin_index == len(coins):
1825
return 0
1926

20-
ways = 0
21-
for coin_index in range(len(coins)):
22-
coin = coins[coin_index]
23-
count_of_coin = 1
24-
while coin * count_of_coin <= total:
25-
total_from_coins = coin * count_of_coin
26-
if total_from_coins == total:
27-
ways += 1
28-
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
30-
ways += intermediate
31-
count_of_coin += 1
27+
coin = coins[coin_index]
28+
29+
if coin > total:
30+
ways = ways_to_make_change_helper(total, coin_index + 1)
31+
else:
32+
ways = (ways_to_make_change_helper(total - coin, coin_index) + ways_to_make_change_helper(total, coin_index + 1))
33+
34+
cache[key] = ways
3235
return ways

0 commit comments

Comments
 (0)