Memoization and Decorators with Python

Nabil Khaja
Mar 22, 2017 · 4 min read
# iterative
def fib_iterative(n):
if (n == 0):
return 0
elif (n == 1):
return 1
elif (n >1 ):
fn = 0
fn1 = 1
fn2 = 2
for i in range(3, n):
fn = fn1+fn2
fn1 = fn2
fn2 = fn
return fn
# recursive
def fib(n):
if n == 0:return 0
if n == 1:return 1
else: return fib(n-1) + fib(n-2)

Memoization: You can have your Cake and Eat it Too!

__fib_cache = {}def fib_memo(n):
if n in __fib_cache:
return __fib_cache[n]

else:
__fib_cache[n] = n if n < 2 else fib_memo(n-2) + fib_memo(n-1)
return __fib_cache[n]

Decorators : Functions using functions to perform other Functions

def memoize(func):
cache = func.cache = {}
@functools.wraps(func)
def memoized_func(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return memoized_func@memoize
def fibonacci(n):
if n == 0:return 0
if n == 1:return 1
else: return fib(n-1) + fib(n-2)

What is @functools.wraps?

Try it yourself!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade