(编辑:jimmy 日期: 2024/11/11 浏览:2)
代码如下:
import functools def memoize(fn): print('start memoize') known = dict() @functools.wraps(fn) def memoizer(*args): if args not in known: print('memorize %s'%args) # known[args] = fn(*args) for k in known.keys(): print('%s : %s'%(k, known[k]), end = ' ') print() # return known[args] return memoizer @memoize def nsum(n): print('now is %s'%n) assert (n >= 0), 'n must be >= 0' return 0 if n == 0 else n + nsum(n - 1) @memoize def fibonacci(n): assert (n >= 0), 'n must be >= 0' return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2) if __name__ == '__main__': print(nsum(10)) print(fibonacci(10))
输出如下:
start memoize
start memoize
memorize 10None
memorize 10None
对比代码(把注释的地方去掉后)的输出:
start memoize start memoize memorize 10 now is 10 memorize 9 now is 9 memorize 8 now is 8 memorize 7 now is 7 memorize 6 now is 6 memorize 5 now is 5 memorize 4 now is 4 memorize 3 now is 3 memorize 2 now is 2 memorize 1 now is 1 memorize 0 now is 0 (0,) : 0 (0,) : 0 (1,) : 1 (0,) : 0 (1,) : 1 (2,) : 3 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (6,) : 21 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (6,) : 21 (7,) : 28 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (6,) : 21 (7,) : 28 (8,) : 36 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (6,) : 21 (7,) : 28 (8,) : 36 (9,) : 45 (0,) : 0 (1,) : 1 (2,) : 3 (3,) : 6 (4,) : 10 (5,) : 15 (6,) : 21 (7,) : 28 (8,) : 36 (9,) : 45 (10,) : 55
通过取消注释的对比,可以得到如下结论:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。