Skip to content

Commit 2c5b468

Browse files
London | 26-SDC-Mar | beko | Sprint 2 | improve code with caches
1 parent e718fb4 commit 2c5b468

2 files changed

Lines changed: 36 additions & 16 deletions

File tree

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
1+
2+
cache = {}
3+
14
def fibonacci(n):
5+
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+
else:
12+
cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
13+
14+
return cache[n]
Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,42 @@
11
from typing import List
22

3+
cache = {}
34

45
def ways_to_make_change(total: int) -> int:
56
"""
67
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.
78
89
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.
910
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
11+
coins = [200, 100, 50, 20, 10, 5, 2, 1]
12+
ways = [0] * (total + 1)
13+
ways[0] = 1
14+
15+
for coin in coins:
16+
for amount in range(coin, total + 1):
17+
ways[amount] += ways[amount - coin]
18+
19+
20+
return ways[total]
1121

1222

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
23+
def ways_to_make_change_helper(total: int, coins: List[int], coin_start_index: int = 0) -> int:
1424
"""
1525
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1626
"""
17-
if total == 0 or len(coins) == 0:
27+
if total == 0:
28+
return 1
29+
if total < 0 or coin_start_index >= len(coins):
1830
return 0
1931

20-
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
32+
memo_key = (total, coin_start_index)
33+
if memo_key in cache:
34+
return cache[memo_key]
35+
36+
coin = coins[coin_start_index]
37+
ways = ways_to_make_change_helper(total, coins, coin_start_index + 1)
38+
if coin <= total:
39+
ways += ways_to_make_change_helper(total - coin, coins, coin_start_index)
40+
41+
cache[memo_key] = ways
3242
return ways

0 commit comments

Comments
 (0)