This is a practical example. Take a look at the sum of a Fibonacci series with and without a record.
from functools import wraps
def memo(func):
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
def fib(i):
if i < 2: return 1
return fib(i-1) + fib(i-2)
@memo
def fib_memo(i):
if i < 2: return 1
return fib_memo(i-1) + fib_memo(i-2)
And now check the speed difference!
>>> print fib(200)
...
>>> print fib_memo(200)
...
source
share