From 2f5217e615188c1b3de94d40aecd9dc11102ac37 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 12 Jan 2026 15:49:25 +0000 Subject: [PATCH] Implementation o fibonnaci sequence --- Sprint-2/improve_with_caches/fibonacci/fibonacci.py | 13 +++++++++++-- .../making_change/making_change.py | 9 +++++++++ 2 files changed, 20 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..ccceec1 100644 --- a/Sprint-2/improve_with_caches/fibonacci/fibonacci.py +++ b/Sprint-2/improve_with_caches/fibonacci/fibonacci.py @@ -1,4 +1,13 @@ +cache = {} + def fibonacci(n): + if n in cache: + return cache[n] + if n <= 1: - return n - return fibonacci(n - 1) + fibonacci(n - 2) + result = n + else: + result = fibonacci(n - 1) + fibonacci(n - 2) + + cache[n] = result + return result 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..a2f0240 100644 --- a/Sprint-2/improve_with_caches/making_change/making_change.py +++ b/Sprint-2/improve_with_caches/making_change/making_change.py @@ -1,6 +1,8 @@ from typing import List +cache = {} + 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. @@ -14,6 +16,11 @@ 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. """ + # Create a cache key from total and coins tuple + cache_key = (total, tuple(coins)) + if cache_key in cache: + return cache[cache_key] + if total == 0 or len(coins) == 0: return 0 @@ -29,4 +36,6 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int: intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:]) ways += intermediate count_of_coin += 1 + + cache[cache_key] = ways return ways