Skip to content

Commit facef1e

Browse files
committed
Optimize Fibonacci and Making Change functions with caching for improved performance
1 parent e718fb4 commit facef1e

File tree

2 files changed

+33
-16
lines changed

2 files changed

+33
-16
lines changed
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
def fibonacci(n):
1+
def fibonacci(n, cache={}):
2+
'''Adding a dictionary to store a copy of what we have already calculated, the complexity becomes linear.
3+
With the cache, each value is computed once, bringing it down to O(n)
4+
'''
25
if n <= 1:
36
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
7+
8+
if n in cache:
9+
return cache[n]
10+
11+
cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache)
12+
return cache[n]

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,35 @@ def ways_to_make_change(total: int) -> int:
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+
cache = {}
11+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], 0, cache)
1112

1213

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
def ways_to_make_change_helper(
15+
total: int, coins: List[int], coin_index: int, cache: dict
16+
) -> int:
1417
"""
1518
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1619
"""
17-
if total == 0 or len(coins) == 0:
20+
if total == 0:
21+
return 1
22+
if coin_index == len(coins):
1823
return 0
1924

25+
key = (total, coin_index)
26+
if key in cache:
27+
return cache[key]
28+
29+
coin = coins[coin_index]
2030
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
31+
32+
# the remaining coins can complete whatever total is left over
33+
while coin * count <= total:
34+
ways += ways_to_make_change_helper(total - coin * count, coins, coin_index + 1, cache)
35+
count += 1
36+
37+
# counting combinations that don't use the current coin
38+
ways += ways_to_make_change_helper(total, coins, coin_index + 1, cache)
39+
40+
cache[key] = ways
3241
return ways

0 commit comments

Comments
 (0)