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

前端 未结 17 2869
佛祖请我去吃肉
佛祖请我去吃肉 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 05:02

    Of course Fibonacci numbers can be computed in O(n) by applying the Binet formula:

    from math import floor, sqrt
    
    def fib(n):                                                     
        return int(floor(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))+0.5))
    

    As the commenters note it's not O(1) but O(n) because of 2**n. Also a difference is that you only get one value, while with recursion you get all values of Fibonacci(n) up to that value.

提交回复
热议问题