Memoization explained using a python implementation of fibonacci
geeklogs.posterous.com
geeklogs.posterous.com
"Memoization is a computer science concept to optimize programs by avoiding computations that have already been done and to reuse it. This is achieved by storing the computaions in a lookup table and retrieving them if a need for it arrives in a future computation step."
From Wikipedia:
"In computer engineering, a cache (/ˈkæʃ/ kash[1]) is a component that transparently stores data so that future requests for that data can be served faster. The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere. If requested data is contained in the cache (cache hit), this request can be served by simply reading the cache, which is comparatively faster." (Emphasis mine.)
fib_val = fib_mem(n-1) + fib_val(n-2)
The second term on the rhs should be fib_mem(n-2) or perhaps even fib_list[n-2].- "if len(list) > n" should probably be "if n in list".
- The function has a side effect (changing the list), this is to be avoided when avoidable
- Memoization is not part of the logic, thus is better done with a decorator (which would solve above side effect issue)
memo5 = {0:0,1:1}
def fib_mem5(n):
try:
return memo5[n]
except KeyError:
memo5[n] = fib_mem5(n-1)+fib_mem5(n-2)
return memo5[n]
Note: the above version runs faster than the cleaner: memo6 = {0:0,1:1}
def fib_mem6(n):
if n in memo6:
return memo6[n]
memo6[n] = fib_mem6(n-1)+fib_mem6(n-2)
return memo6[n]Edit: hm, in my casual testing, the 'cleaner' version takes about 10% longer.
To me, the memoized version is more clear and should be just as efficient as the iterative version. However, this version of fib_mem dies before fib_mem(1000)!
Apparently, you can increase the recursion depth limit using the sys module. Is that the right thing to do? And, if you do it, are there guidelines for doing so without causing memory problems?
In many cases, a better solution is to implement tail recursion, which can be done quite easily. See http://paulbutler.org/archives/tail-recursion-in-python/ .
http://matt.might.net/articles/implementation-of-recursive-f...
The example is also Fibonacci.
The diagrams make it easy to understand. It is in groovy though.