Skip to content

Commit 7e20d44

Browse files
committed
add caching to improve performance
1 parent e718fb4 commit 7e20d44

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed
Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1+
cache = {}
2+
13
def fibonacci(n):
24
if n <= 1:
35
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
6+
7+
if n in cache:
8+
return cache[n]
9+
10+
cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
11+
return cache[n]
Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
from typing import List
22

3+
cache = {}
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.
7-
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-
"""
106
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
117

128

139
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:
10+
key = (total, tuple(coins))
11+
12+
if key in cache:
13+
return cache[key]
14+
15+
if total == 0:
16+
return 1
17+
18+
if total < 0 or len(coins) == 0:
1819
return 0
1920

2021
ways = 0
@@ -26,7 +27,11 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2627
if total_from_coins == total:
2728
ways += 1
2829
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
30-
ways += intermediate
30+
ways += ways_to_make_change_helper(
31+
total - total_from_coins,
32+
coins=coins[coin_index + 1:]
33+
)
3134
count_of_coin += 1
32-
return ways
35+
36+
cache[key] = ways
37+
return ways

0 commit comments

Comments
 (0)