Skip to content

London | Nadika Zavodovska | Module-Complexity | Sprint 2 | Improve with caches #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions Sprint-2/improve_with_caches/fibonacci/fibonacci.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
# Dictionary to store the answers
cache = {}

def fibonacci(n):
# If we already know the answer, just use it
if n in cache:
return cache[n]

# The first two numbers in Fibonacci are 0 and 1
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
result = n
else:
# Else find the result by adding the two previous numbers
result = fibonacci(n - 1) + fibonacci(n - 2)

# Remember this result so we don’t calculate it again later
cache[n] = result
return result
18 changes: 16 additions & 2 deletions Sprint-2/improve_with_caches/making_change/making_change.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import List

# Dictionary to store already-computed results
cache = {}

def ways_to_make_change(total: int) -> int:
"""
Expand All @@ -13,8 +15,15 @@ def ways_to_make_change(total: int) -> int:
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
"""
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
Uses caching to speed up repeated calculations.
"""
if total == 0 or len(coins) == 0:
key = (total, tuple(coins))
if key in cache:
return cache[key]

if total == 0:
return 1
if len(coins) == 0 or total < 0:
return 0

ways = 0
Expand All @@ -26,7 +35,12 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
if total_from_coins == total:
ways += 1
else:
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
intermediate = ways_to_make_change_helper(
total - total_from_coins,
coins=coins[coin_index + 1:]
)
ways += intermediate
count_of_coin += 1

cache[key] = ways
return ways