Last active
December 31, 2024 04:02
-
-
Save msyvr/48003acc1498d293c281a7b64178b141 to your computer and use it in GitHub Desktop.
mit 6.0001 Fibonacci - dynamic programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib_eff(n, dict): | |
''' | |
performace-aware recursive algorithm: | |
keep track of computed Fibonacci terms in a dictionary; | |
limit computation to terms not in the dictionary | |
''' | |
if n in dict: | |
return dict[n] | |
else: | |
fibn = fib_eff(n-1, dict) + fib_eff(n-2, dict) | |
dict[n] = fibn | |
return fibn | |
if __name__ == "__main__": | |
dict = {0:1, 1:1} | |
n = int(input('Which Fibonacci term?: ')) | |
print(f'Fibonacci term {n} is {fib_eff(n, dict)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment