From b90b5f359ff1b8892fbffa3b4522de93c52bcf7c Mon Sep 17 00:00:00 2001 From: nadika Date: Wed, 18 Jun 2025 22:43:18 +0100 Subject: [PATCH 1/2] Implove with caches fibonacci --- .../improve_with_caches/fibonacci/fibonacci.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Sprint-2/improve_with_caches/fibonacci/fibonacci.py b/Sprint-2/improve_with_caches/fibonacci/fibonacci.py index 60cc667..0be6ae7 100644 --- a/Sprint-2/improve_with_caches/fibonacci/fibonacci.py +++ b/Sprint-2/improve_with_caches/fibonacci/fibonacci.py @@ -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 From 16a4ad85e44e51ba81e9d5aa5bd574983a8384df Mon Sep 17 00:00:00 2001 From: nadika Date: Thu, 19 Jun 2025 10:43:17 +0100 Subject: [PATCH 2/2] Improve with caches making change --- .../making_change/making_change.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Sprint-2/improve_with_caches/making_change/making_change.py b/Sprint-2/improve_with_caches/making_change/making_change.py index 255612e..2913331 100644 --- a/Sprint-2/improve_with_caches/making_change/making_change.py +++ b/Sprint-2/improve_with_caches/making_change/making_change.py @@ -1,5 +1,7 @@ from typing import List +# Dictionary to store already-computed results +cache = {} def ways_to_make_change(total: int) -> int: """ @@ -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 @@ -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