Skip to content

Commit 7c58ae2

Browse files
committed
amended fibonacci and making change cache
1 parent cf9e042 commit 7c58ae2

File tree

2 files changed

+19
-17
lines changed

2 files changed

+19
-17
lines changed
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
def fibonacci(n):
1+
def fibonacci(n, cache={}):
22
if n <= 1:
33
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
4+
if n in cache:
5+
return cache[n]
6+
result = fibonacci(n - 1) + fibonacci(n - 2)
7+
cache[n] = result
8+
return result
Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,15 @@
11
from typing import List
22

3-
43
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.
7-
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])
4+
cache = {}
5+
return ways_to_make_change_helper(total, (200, 100, 50, 20, 10, 5, 2, 1), cache)
116

12-
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-
"""
7+
def ways_to_make_change_helper(total: int, coins: tuple, cache: dict) -> int:
178
if total == 0 or len(coins) == 0:
189
return 0
19-
10+
cache_key = (total, coins)
11+
if cache_key in cache:
12+
return cache[cache_key]
2013
ways = 0
2114
for coin_index in range(len(coins)):
2215
coin = coins[coin_index]
@@ -26,7 +19,12 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2619
if total_from_coins == total:
2720
ways += 1
2821
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
22+
intermediate = ways_to_make_change_helper(
23+
total - total_from_coins,
24+
coins=coins[coin_index + 1:],
25+
cache=cache
26+
)
3027
ways += intermediate
3128
count_of_coin += 1
32-
return ways
29+
cache[cache_key] = ways
30+
return ways

0 commit comments

Comments
 (0)