Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 10 additions & 3 deletions Sprint-2/improve_with_caches/fibonacci/fibonacci.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
def fibonacci(n):
if n <= 1:

def fibonacci(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo)
return memo[n]

# Time complexity: O(n)
# # Space complexity: O(n) due to the memo dictionary
1 change: 0 additions & 1 deletion Sprint-2/improve_with_caches/fibonacci/fibonacci_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import unittest

from fibonacci import fibonacci

class FibonacciTest(unittest.TestCase):
Expand Down
31 changes: 22 additions & 9 deletions Sprint-2/improve_with_caches/making_change/making_change.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
from typing import List


def ways_to_make_change(total: int) -> int:
"""
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.

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


def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
"""
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
Helper function with memoization.
Cache key is (total, index of first coin in list) — but since we pass
the coins list by slicing, we can cache using tuple(total, tuple(coins)).
"""

key = (total, tuple(coins))

if key in cache:
return cache[key]

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

Expand All @@ -26,7 +33,13 @@ 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:],
cache=cache
)
ways += intermediate
count_of_coin += 1
return ways

cache[key] = ways
return ways
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import unittest

from making_change import ways_to_make_change

class MakingChangeTest(unittest.TestCase):
Expand Down