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

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

    As @alex suggested, you could use a generator function to do this sequentially instead of recursively.

    Here's the equivalent of the code in your question:

    def fib(n):
        def fibseq(n):
            """ Iteratively return the first n Fibonacci numbers, starting from 0. """
            a, b = 0, 1
            for _ in xrange(n):
                yield a
                a, b = b, a + b
    
        return sum(v for v in fibseq(n))
    
    print format(fib(100000), ',d')  # -> no recursion depth error
    

提交回复
热议问题