我正在使用Think in Python进行练习,使用Memo计算Fibonacci序列比不使用它更有效。但是当实施它并测试消耗的时间时,我发现运行时间根本没有减少。我知道我的节目肯定有问题,有人可以告诉我哪里出错了。非常感谢。
import time
known = {0:0,1:1}
def fibonacci_memo(n):
"""return the nth number of fibonacci sequence
using memo to raise efficiency"""
if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res
def fibonacci(n):
"""return the nth number of fibonacci sequence
without using memo"""
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == '__main__':
start = time.clock()
print fibonacci_memo(32)
elaspsed = time.clock() - start
print 'using memo time used: ' + str(elaspsed)
start = time.clock()
print fibonacci(32)
elaspsed = time.clock() - start
print 'without using memo time used: ' + str(elaspsed)
输出类似于:
2178309
using memo time used: 1.83040345779
2178309
without using memo time used: 1.792043347
答案 0 :(得分:3)
你的fibonacci_memo函数不是递归调用自己,而是调用原始的(非memoized)fibonacci函数。
答案 1 :(得分:2)
memoized函数的递归调用了一个不同的函数。尝试用以下方法替换fibonacci_memo:
def fibonacci_memo(n):
"""return the nth number of fibonacci sequence
using memo to raise efficiency"""
if n in known:
return known[n]
res = fibonacci_memo(n-1) + fibonacci_memo(n-2)
known[n] = res
return res