简体   繁体   中英

Python recursion test in PyCharm - Process finished with exit code 139

System: Ubuntu 14

IDE: PyCharm Community Edition 3.1.1

Python: 2.7.6

Algorithm with recurrent call:

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

Test:

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)

Value in test is intended. Around value 26175 test sometimes pass but sometimes it is terminated with message: Process finished with exit code 139 I understand that test result somehow depends from hardware resources but I'm looking for more precise answer from stackoverflow seniors :)

You can use non-recursive algorithm to calculate Fibonacci numbers

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)

Or use the formula:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM