What is the maximum recursion depth in Python, and how to increase it?

前端 未结 17 2966
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:14

I have this tail recursive function here:

def recursive_function(n, sum):
    if n < 1:
        return sum
    else:
        return recursive_function(n-1         


        
17条回答
  •  面向向阳花
    2020-11-21 04:53

    If you want to get only few Fibonacci numbers, you can use matrix method.

    from numpy import matrix
    
    def fib(n):
        return (matrix('0 1; 1 1', dtype='object') ** n).item(1)
    

    It's fast as numpy uses fast exponentiation algorithm. You get answer in O(log n). And it's better than Binet's formula because it uses only integers. But if you want all Fibonacci numbers up to n, then it's better to do it by memorisation.

提交回复
热议问题