Skip to content

Commit 391df35

Browse files
committed
refactor(fibonacci): use function attribute for persistent memoization cache
1 parent 4d665b2 commit 391df35

1 file changed

Lines changed: 9 additions & 8 deletions

File tree

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
def fibonacci(n):
2-
# Initialize the cache dictionary
3-
cache = {}
2+
# Initialize the cache as a function attribute if it doesn't exist yet
3+
if not hasattr(fibonacci, "cache"):
4+
fibonacci.cache = {}
45

56
def helper(number):
6-
# Check the cache at the start
7-
if number in cache:
8-
return cache[number]
7+
# Check the function attribute cache at the start
8+
if number in fibonacci.cache:
9+
return fibonacci.cache[number]
910

1011
# Base case
1112
if number <= 1:
@@ -14,8 +15,8 @@ def helper(number):
1415
# Compute the result (making sure number decreases!)
1516
result = helper(number - 1) + helper(number - 2)
1617

17-
# Store the result in the cache right before returning
18-
cache[number] = result
18+
# Store the result in the function attribute cache right before returning
19+
fibonacci.cache[number] = result
1920
return result
2021

21-
return helper(n)
22+
return helper(n)

0 commit comments

Comments
 (0)