我一直在努力将斐波那契数列中的每个数字写入文件,我知道我做错了什么,但我无法确定它。有没有更有效的方法?任何帮助表示赞赏。
import sys
import os
import time
known = {0:0, 1:1}
def fibonacci_slow(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_slow(n-1) + fibonacci_slow(n-2)
def fibonacci_fast(n):
f = open('fib500.txt', 'w')
if n in known:
return known[n]
res = fibonacci_fast(n-1) + fibonacci_fast(n-2)
print res
if fibonacci_fast:
f.write(res)
known[n] = res
return res
def main():
time_start = time.time()
print fibonacci_slow(10)
time_end = time.time()
print "Time for slow fibonacci to complete ", time_end - time_start
time_start = time.time()
print fibonacci_fast(500)
time_end = time.time()
print "Time for fast fibonacci to complete ", time_end - time_start
if __name__ == '__main__':
main()