Here's a little piece of code which converts every function to its memoization version.
def memoize(f): # Memoize a given function f
def memf(*x):
if x not in memf.cache:
memf.cache[x] = f(*x)
return memf.cache[x]
memf.cache = {}
return memf
For instance, if we have a function fib as follows which returns the nth Fibonacci number:
def fib(n):
if n < 2:
return 1
else:
return fib(n-1) + fib(n-2)
Now, the above function can be memoized by using
fib = memoize(fib)
Everything is fine up to this point but what I can't understand is that if we do something like this, instead of:
fib = memoize(fib)
we instead do:
fib2 = memoize(fib)
the function fib2 isn't a memoized function of fib. When we run fib2 it runs like ordinary fib. Please explain why this memoize function gets applied to say a function f if and only if we use:
f = memoize(f)
The memoization code is taken from 6.00x a MOOC provided by edx.org. It's not running right now that's why I have come here to ask.