Skip to content

Commit 527cba8

Browse files
committed
Add dic cache and math check
1 parent cf9e042 commit 527cba8

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed
Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1+
memo = {}
2+
13
def fibonacci(n):
4+
if n in memo:
5+
return memo[n]
6+
27
if n <= 1:
38
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
9+
result = fibonacci(n - 1) + fibonacci(n - 2)
10+
memo[n] = result
11+
12+
return result

Sprint-2/improve_with_caches/making_change/making_change.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,34 @@
11
from typing import List
2-
3-
2+
cache = {}
43
def ways_to_make_change(total: int) -> int:
54
"""
65
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.
76
87
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.
98
"""
9+
10+
cache.clear()
1011
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
1112

1213

1314
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
1415
"""
1516
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1617
"""
18+
key = (total, tuple(coins))
19+
20+
if key in cache:
21+
return cache[key]
22+
1723
if total == 0 or len(coins) == 0:
1824
return 0
19-
25+
26+
if len(coins) == 1:
27+
if total % coins[0] == 0:
28+
return 1
29+
else:
30+
return 0
31+
2032
ways = 0
2133
for coin_index in range(len(coins)):
2234
coin = coins[coin_index]
@@ -29,4 +41,5 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2941
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
3042
ways += intermediate
3143
count_of_coin += 1
44+
cache[key] = ways
3245
return ways

0 commit comments

Comments
 (0)