PyCharm中的Python递归测试 - 进程以退出代码139完成

时间:2014-05-10 07:52:10

标签: python python-2.7 ubuntu recursion pycharm

系统: Ubuntu 14

IDE: PyCharm Community Edition 3.1.1

Python: 2.7.6

具有循环调用的算法:

def fibonacci_dynamic(n):
    if n == 0:
       return 0
    if n == 1:
       return 1
    computed_values = {1: 1, 2: 1}
    return memoize(n, computed_values)


def memoize(n, computed_values):
    if n in computed_values:
        return computed_values[n]
    #recurrent call
    computed_values[n - 1] = memoize(n - 1, computed_values)
    computed_values[n - 2] = memoize(n - 2, computed_values)
    new_value = computed_values[n - 1] + computed_values[n - 2]
    computed_values[n] = new_value
    return new_value

测试:

from unittest import TestCase
from first.fib.fibonacci import fibonacci_dynamic
import sys
sys.setrecursionlimit(40000)


class TestFibonacci_dynamic_param(TestCase):

    def test_fibonacci_dynamic_26175(self):
        result = fibonacci_dynamic(26175)
        self.assertIsNotNone(result)

测试中的值是有意的。值26175附近测试有时会通过,但有时它会以消息终止: Process finished with exit code 139 我知道测试结果在某种程度上取决于硬件资源,但我正在寻找来自stackoverflow老年人的更精确答案:)

1 个答案:

答案 0 :(得分:1)

您可以使用非递归算法计算斐波纳契数

class FibonacciNumbers(object):
    def __init__(self):
        self._fib = [0, 1, 1] #first three fibonacci numbers

    def get(self, n):
        if n < len(self._fib):
            return self._fib[n]
        for i in xrange(len(self._fib), n+1):
            self._fib.append(self._fib[i-1] + self._fib[i-2])
        return self._fib[-1]


fib = FibonacciNumbers()
print fib.get(0)
print fib.get(1000)

或使用公式: