Skip to content

Commit d5efde9

Browse files
committed
improve_with_cache
1 parent e718fb4 commit d5efde9

2 files changed

Lines changed: 30 additions & 16 deletions

File tree

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1+
cache = {}
2+
13
def fibonacci(n):
24
if n <= 1:
35
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
6+
if n in cache:
7+
return cache[n]
8+
else:
9+
cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
10+
return cache[n]
Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,40 @@
11
from typing import List
2-
2+
cache = {}
3+
COINS = [200, 100, 50, 20, 10, 5, 2, 1]
4+
COINT_TYPES_NUM = len(COINS)
35

46
def ways_to_make_change(total: int) -> int:
57
"""
68
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
810
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.
911
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
12+
return ways_to_make_change_helper(total, 0)
1113

1214

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
15+
def ways_to_make_change_helper(total: int, coin_index: int) -> int:
1416
"""
1517
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1618
"""
17-
if total == 0 or len(coins) == 0:
19+
if (total, coin_index) in cache:
20+
return cache[(total, coin_index)]
21+
22+
if total == 0:
23+
return 1
24+
25+
if coin_index == COINT_TYPES_NUM:
1826
return 0
1927

28+
2029
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
30+
coin = COINS[coin_index]
31+
count_of_coin = 0
32+
while count_of_coin * coin <= total:
33+
ways += ways_to_make_change_helper(
34+
total - count_of_coin * coin,
35+
coin_index + 1
36+
)
37+
count_of_coin += 1
38+
39+
cache[(total, coin_index)] = ways
3240
return ways

0 commit comments

Comments
 (0)