Skip to content

Commit 9f5699d

Browse files
committed
correction
1 parent 9e40a33 commit 9f5699d

2 files changed

Lines changed: 16 additions & 23 deletions

File tree

‎Sprint-2/improve_with_caches/fibonacci/fibonacci.py‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
cache = {
2-
0: 0,
3-
1: 1
4-
}
5-
61
def fibonacci(n):
72
if n <= 1:
83
return n
Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List
1+
COINS = (200, 100, 50, 20, 10, 5, 2, 1)
22
cache = {}
33

44

@@ -8,34 +8,32 @@ def ways_to_make_change(total: int) -> int:
88
99
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.
1010
"""
11-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
11+
return ways_to_make_change_helper(total, 0)
1212

1313

14-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
def ways_to_make_change_helper(total: int, coin_index: int) -> int:
1515
"""
1616
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1717
"""
18-
key = (total, tuple(coins))
18+
key = (total, coin_index)
1919

2020
if key in cache:
2121
return cache[key]
2222

23-
if total == 0 or len(coins) == 0:
23+
if total == 0:
24+
return 1
25+
26+
if total < 0 or coin_index >= len(COINS):
2427
return 0
2528

26-
ways = 0
27-
for coin_index in range(len(coins)):
28-
coin = coins[coin_index]
29-
count_of_coin = 1
30-
while coin * count_of_coin <= total:
31-
total_from_coins = coin * count_of_coin
32-
if total_from_coins == total:
33-
ways += 1
34-
else:
35-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
36-
ways += intermediate
37-
count_of_coin += 1
29+
coin = COINS[coin_index]
30+
31+
# Option 1: Skip this coin and move to the next denomination.
32+
ways = ways_to_make_change_helper(total, coin_index + 1)
33+
34+
# Option 2: Use this coin and consider it again.
35+
if coin <= total:
36+
ways += ways_to_make_change_helper(total - coin, coin_index)
3837

3938
cache[key] = ways
4039
return ways
41-

0 commit comments

Comments
 (0)