Python脚本崩溃,我不知道为什么

时间:2014-01-28 17:15:54

标签: python fibonacci

所以我有2个python程序来确定斐波纳契数。一个使用memoinization而另一个不使用memoinization。两者都有效,并且能够在给定输入时确定数字。

但是,我需要计算时间,这是第3个程序发挥作用的地方。我把第一个纤维数的两个函数定时到第30个。当我运行第三个程序时,它似乎在计算第9个数字时就废弃了,我不知道为什么。

有人可以帮助我吗?我有下面所有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)

计划3:

#!/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)

ERROR:

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'

1 个答案:

答案 0 :(得分:3)

if n in cache是错误的逻辑。您可能想要if cache[n] is not None

n应该代表第n个斐波纳契数,因此缓存存储斐波那契数字,而不是它们的指示。