所以我有2個python程序確定斐波納契數字。一個使用memoinization,另一個不使用。兩者都可以工作,並且能夠在給出輸入時確定數字。Python腳本崩潰,我不知道爲什麼
但是,我需要對它們進行計時,這是第三個程序進入的地方。我已經確定了第一個fib數到第三十的兩個函數。當我運行第三個程序的時候,它似乎在計算第九個數字的時候就是廢話,我不知道爲什麼。
有人可以幫我嗎?我對所有3個項目下面的代碼(和錯誤)
感謝
計劃1
#!/usr/bin/python
import sys
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
numIn = int(sys.argv[1])
result = fib(numIn)
print 'The %dth fibonacci number is %d' % (numIn, result)
方案2:
#!/usr/bin/python
import sys
cache = [None]*100
def fib(n):
if n in cache:
return cache[n]
else:
if n < 2:
cache[n] = n
else:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
numIn = int(sys.argv[1])
result = fib(numIn)
print 'The %dth fibonacci number is %d' % (numIn, result)
方案三:
#!/usr/bin/python
import sys,timeit,time
for i in range(1, 30):
t1 = timeit.Timer('fib(%s)' % i, 'from problem1 import fib').timeit()
t2 = timeit.Timer('fib(%s)' % i, 'from problem2 import fib').timeit()
print 'The time for the %d th number is %f (Problem 1 - No Memo' % (i,t1)
print 'The time for the %d th number is %f (Problem 1 - Memo' % (i,t2)
錯誤:
The 5th fibonacci number is 5
The 5th fibonacci number is 5
The time for the 1 th number is 0.215671 (Problem 1 - No Memo
The time for the 1 th number is 0.247929 (Problem 1 - Memo
The time for the 2 th number is 0.606024 (Problem 1 - No Memo
The time for the 2 th number is 0.269888 (Problem 1 - Memo
The time for the 3 th number is 1.027372 (Problem 1 - No Memo
The time for the 3 th number is 0.298666 (Problem 1 - Memo
The time for the 4 th number is 1.839900 (Problem 1 - No Memo
The time for the 4 th number is 4.466314 (Problem 1 - Memo
The time for the 5 th number is 3.117439 (Problem 1 - No Memo
The time for the 5 th number is 0.308327 (Problem 1 - Memo
The time for the 6 th number is 5.178429 (Problem 1 - No Memo
The time for the 6 th number is 8.496127 (Problem 1 - Memo
The time for the 7 th number is 8.486079 (Problem 1 - No Memo
The time for the 7 th number is 12.532179 (Problem 1 - Memo
The time for the 8 th number is 13.571108 (Problem 1 - No Memo
The time for the 8 th number is 0.321315 (Problem 1 - Memo
Traceback (most recent call last):
File "./problem3.py", line 7, in <module>
t2 = timeit.Timer('fib(%s)' % i, 'from problem2 import fib').timeit()
File "/usr/lib/python2.7/timeit.py", line 195, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
File "problem2.py", line 18, in fib
cache[n] = fib(n-1) + fib(n-2)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
那麼錯誤是什麼? –
你從錯誤中得出了什麼結論(現在你已經更新了這篇文章)?例如,你是否嘗試用pdb執行程序? –