Minimalistic Memoization in python, just works, doesn't take care of cleaning up the cache however.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def fib(n):
if n==1 or n==0:
return 1
return fib(n-2) + fib(n-1)
def memoize(f):
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
fib = memoize(fib)
print fib(969)
|
If we use memoize function as a python decorator, than IMHO code looks more pythonic Don't know though if decorators were not used on purpose.
Well, I quite agree. This is neater and more pythonic.
In the first code snippet, I was also trying to show (in a presentation to some colleagues) what it means for functions to be first class citizens in a language, i.e. you can pass functions as parameters to other functions, you can return functions as return values from other functions, and you can assign them to variable names.
It also would work if the function is not your code, but imported from some other script, and it will affect this function only in the local context or scope.
Finally, I am not quite familiar with decorators to be honest :) will work on that.