Skip to content

Commit 57900a7

Browse files
committed
improve_with_caches task id completed
1 parent f13588d commit 57900a7

2 files changed

Lines changed: 39 additions & 13 deletions

File tree

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,15 @@
1+
2+
cache = {}
3+
4+
15
def fibonacci(n):
6+
if n in cache:
7+
return cache[n]
8+
29
if n <= 1:
310
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
11+
12+
result = fibonacci(n - 1) + fibonacci(n - 2)
13+
cache[n] = result
14+
15+
return result
Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,47 @@
1+
12
from typing import List
23

34

45
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.
6+
cache = {}
7+
coins = [200, 100, 50, 20, 10, 5, 2, 1]
8+
9+
return ways_to_make_change_helper(total, coins, cache)
710

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])
1111

12+
def ways_to_make_change_helper(
13+
total: int, coins: List[int], cache: dict
14+
) -> int:
15+
if total == 0:
16+
return 1
1217

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:
18+
if len(coins) == 0:
1819
return 0
1920

21+
key = (total, tuple(coins))
22+
23+
if key in cache:
24+
return cache[key]
25+
2026
ways = 0
27+
2128
for coin_index in range(len(coins)):
2229
coin = coins[coin_index]
2330
count_of_coin = 1
31+
2432
while coin * count_of_coin <= total:
2533
total_from_coins = coin * count_of_coin
34+
2635
if total_from_coins == total:
2736
ways += 1
2837
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
30-
ways += intermediate
38+
ways += ways_to_make_change_helper(
39+
total - total_from_coins,
40+
coins[coin_index + 1:],
41+
cache,
42+
)
43+
3144
count_of_coin += 1
45+
46+
cache[key] = ways
3247
return ways

0 commit comments

Comments
 (0)