In many memoization examples, I usually see people prefer to make a wrapper or decorator (or some language-dependent variations, such as using a higher-order function to close the memo object) to keep the results of previous function calls in an almost “state”. Such an example can be seen below:
class Memoize(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if args in self.cache:
return self.cache[args]
ret = self.func(*args)
self.cache[args] = ret
return ret
@Memoize
def fib(n):
if n < 2:
return 1
return fib(n-2) + fib(n-1)
What is the difference between / tradefoff between doing something this way by simply passing a note in the arguments to your function? For example, for example:
def fib(n, memo = {}):
if (n < 2):
return 1
if (n in memo):
return memo[n]
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
source
share