Skip to content
This repository was archived by the owner on Jan 26, 2024. It is now read-only.

Commit 6d2bec7

Browse files
committed
fibonacci calculation - use memoization to prevent duplicate calculations.
1 parent e437403 commit 6d2bec7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

fast_fibonacci.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Using memoization to speed up fibonacci calculations.
5+
Records computed fib values in a dictionary to prevent duplicate compute time
6+
"""
7+
8+
9+
def fib_memo(num, memo=None):
10+
"""
11+
Assume num >= 0
12+
memo is a dictionary used to prevent duplicate calcuations
13+
"""
14+
15+
if memo is None:
16+
# dictionary not created yet
17+
memo = {}
18+
if num == 0 or num == 1:
19+
# fibonacci base case
20+
return 1
21+
try:
22+
# attempt to lookup the result
23+
return memo[num]
24+
except KeyError:
25+
# result not caculated yet, perform calculation
26+
result = fib_memo(num - 1, memo) + fib_memo(num - 2, memo)
27+
# store result in dictionary
28+
memo[num] = result
29+
return result
30+
31+
32+
print(f"-> Fib of 5 is: {str(fib_memo(5))}")
33+
print(f"-> Fib of 100 is: {str(fib_memo(100))}")

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy