Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active December 31, 2024 04:02
Show Gist options
  • Save msyvr/48003acc1498d293c281a7b64178b141 to your computer and use it in GitHub Desktop.
Save msyvr/48003acc1498d293c281a7b64178b141 to your computer and use it in GitHub Desktop.
mit 6.0001 Fibonacci - dynamic programming
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