Implement Fibonacci

This commit is contained in:
Etienne Zind 2023-02-20 08:40:10 +01:00
parent 15eeaec1f3
commit 6a8a19655a

26
fibonacci.py Normal file
View File

@ -0,0 +1,26 @@
def fibonacci(n: int):
"""Return the n-th Fibonacci number."""
memo: dict[int, int] = {}
"""The memoization register."""
def dp(i: int):
"""Recursive subproblem: return memoized i-th Fibonacci number."""
# check if memoized yet
f = memo.get(i, None)
if f is not None:
return f
# compute actual value, making "free" recursive calls
f = 2 if i <= 2 else dp(i-1) + dp(i-2)
# set the memoization register
memo[i] = f
return f
return dp(n)
print(f"The 9th Fibonacci number is: {fibonacci(9)}")