This is a simplified version of George Sakkis recipe entitled "Cache decorator in python 2.4" (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205). In this version, no extra classes are required and this is small enough to implement on the fly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | def cachable(func):
'''
Cache results of function in func.cache.
-- No keyword args allowed.
'''
func.cache = {}
def out(*args):
if args not in func.cache:
func.cache[args] = func(*args)
return func.cache[args]
return out
# ------------------- test it out --------------------
@cachable
def fibonacci(n):
if n == 0 or n == 1:
out = 1
else:
out = fibonacci(n - 1) + fibonacci(n - 2)
return out
import time
start = time.time()
for i in range(35):
print i, fibonacci(i)
print 'Time:', time.time() - start
# 0.17 Seconds!
|
Tags: algorithms
Nice ! It would be more Pythonic with :
Thanks. I made the change.