Skip to content

Commit 9b61b96

Browse files
committed
Optimize fibonacci: add dictionary cache to speed up recursion
1 parent 134e683 commit 9b61b96

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
1+
# Create a dictionary to use as our "Notepad" (Cache)
2+
memo = {}
3+
14
def fibonacci(n):
5+
# Check if we already calculated this number
6+
if n in memo:
7+
return memo[n]
8+
29
if n <= 1:
310
return n
4-
return fibonacci(n - 1) + fibonacci(n - 2)
11+
12+
result = fibonacci(n - 1) + fibonacci(n - 2)
13+
14+
# Save the result in our Notepad before returning
15+
memo[n] = result
16+
17+
return result

0 commit comments

Comments
 (0)