Skip to content

Commit b4ccdbd

Browse files
committed
speeding up solution for fibonacci and ways_to_make_change by caching
1 parent 134e683 commit b4ccdbd

File tree

2 files changed

+35
-18
lines changed

2 files changed

+35
-18
lines changed
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1+
_fib_cache = {}
2+
13
def fibonacci(n):
4+
if n in _fib_cache:
5+
return _fib_cache[n]
6+
27
if n <= 1:
3-
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
8+
x = n
9+
else:
10+
x = fibonacci(n - 1) + fibonacci(n - 2)
11+
_fib_cache[n] = x
12+
return x
Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,41 @@
1-
from typing import List
2-
1+
# cache dictionary, key is (total, tuple_of_coins)
2+
_change_cache = {}
33

44
def ways_to_make_change(total: int) -> int:
55
"""
66
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.
77
88
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.
99
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
10+
_change_cache.clear()
11+
coins = (200, 100, 50, 20, 10, 5, 2, 1)
12+
return ways_to_make_change_helper(total, tuple(coins))
1113

1214

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
15+
def ways_to_make_change_helper(total: int, coins: tuple) -> int:
1416
"""
1517
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1618
"""
17-
if total == 0 or len(coins) == 0:
19+
if total == 0:
20+
return 1
21+
if not coins:
1822
return 0
1923

24+
key = (total, coins)
25+
if key in _change_cache:
26+
return _change_cache[key]
27+
28+
coin = coins[0]
29+
rest = coins[1:]
30+
2031
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
32+
count_of_coin = 0
33+
34+
while coin * count_of_coin <= total:
35+
total_from_coins = coin * count_of_coin
36+
intermediate = ways_to_make_change_helper(total - total_from_coins, rest)
37+
ways += intermediate
38+
count_of_coin += 1
39+
40+
_change_cache[key] = ways
3241
return ways

0 commit comments

Comments
 (0)