Skip to content

Commit 8b5f0b6

Browse files
Add memoization to fibonacci and making_change for performance improvement
1 parent de683df commit 8b5f0b6

2 files changed

Lines changed: 34 additions & 23 deletions

File tree

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
1+
cache = {}
2+
3+
14
def fibonacci(n):
5+
if n in cache:
6+
return cache[n]
7+
28
if n <= 1:
3-
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
9+
result = n
10+
else:
11+
result = fibonacci(n - 1) + fibonacci(n - 2)
12+
13+
cache[n] = result
14+
return result
Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
11
from typing import List
22

33

4+
cache = {}
5+
coins = [200, 100, 50, 20, 10, 5, 2, 1]
6+
7+
48
def ways_to_make_change(total: int) -> int:
5-
"""
6-
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.
79

8-
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.
9-
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
10+
cache.clear()
11+
return ways_to_make_change_helper(total, 0)
1112

1213

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14-
"""
15-
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
16-
"""
17-
if total == 0 or len(coins) == 0:
14+
def ways_to_make_change_helper(total: int, coin_index: int) -> int:
15+
key = (total, coin_index)
16+
if key in cache:
17+
return cache[key]
18+
19+
if total == 0:
20+
return 1
21+
if coin_index >= len(coins) or total < 0:
1822
return 0
1923

2024
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
25+
coin = coins[coin_index]
26+
count_of_coin = 0
27+
28+
while coin * count_of_coin <= total:
29+
ways += ways_to_make_change_helper(total - (coin * count_of_coin), coin_index + 1)
30+
count_of_coin += 1
31+
32+
cache[key] = ways
3233
return ways

0 commit comments

Comments
 (0)