Save each set of parameters with your respective return value in cache.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Cache:
def __init__(self):
# cache of salf.fatorial()
self.c_fatorial = {}
def fatorial(self, x):
result = 0
# first, verify in cache
if x in self.c_fatorial.keys():
return self.c_fatorial[x]
# if not in cach, process
if x <= 1:
result = 1
else:
result = x * self.fatorial(x - 1)
self.c_fatorial[x] = result # put the result in cache
return result
|
better use this: http://code.activestate.com/recipes/325205-cache-decorator-in-python-24/
Here is why "if x in self.c_factorial.keys()" would slow your cache down - http://blog.ideamonk.in/2010/07/poorly-implementing-caching-in-python.html
"Fail early, fail fast" FTW.