def memoize(fn): stored_results = {} @functools.wrap(fn) def memoized(*args): try: # try to get the cached result return stored_results[args] except KeyError: # nothing was cached for those args. let's fix that. result = stored_results[args] = fn(*args) return result return memoized
使用:
def fib(n): return n if n in [0, 1] else fib(n - 2) + fib(n - 1) fib = memoize(fib)
or
@memoize def fib(n): return n if n in [0, 1] else fib(n - 2) + fib(n - 1)