Created
February 1, 2022 01:03
-
-
Save eecsmap/7d9c455a57d3f676abfe47792514853d to your computer and use it in GitHub Desktop.
memoization in fib examples
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
# visualize the function runtime | |
# using https://pythontutor.com/composingprograms.html#mode=edit | |
def fib0(n): | |
if n < 2: return n | |
return fib0(n - 1) + fib0(n - 2) | |
fib0(3) | |
def fib1(n, m={}): | |
if n < 2: return n | |
if n not in m: | |
m[n] = fib1(n - 1) + fib1(n - 2) | |
return m[n] | |
fib1(3) | |
def memoization(func): | |
m = {} | |
def wrapper(n): | |
if n not in m: | |
m[n] = func(n) | |
return m[n] | |
return wrapper | |
@memoization | |
def fib2(n): | |
if n < 2: return n | |
return fib2(n - 1) + fib2(n - 2) | |
fib2(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment