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

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

    I wanted to give you an example for using memoization to compute Fibonacci as this will allow you to compute significantly larger numbers using recursion:

    cache = {}
    def fib_dp(n):
        if n in cache:
            return cache[n]
        if n == 0: return 0
        elif n == 1: return 1
        else:
            value = fib_dp(n-1) + fib_dp(n-2)
        cache[n] = value
        return value
    
    print(fib_dp(998))
    

    This is still recursive, but uses a simple hashtable that allows the reuse of previously calculated Fibonacci numbers instead of doing them again.

提交回复
热议问题