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)

 

posted on 2013-12-30 14:09  perel  阅读(179)  评论(0编辑  收藏  举报