📜  Python|处理递归限制

📅  最后修改于: 2022-05-13 01:54:29.396000             🧑  作者: Mango

Python|处理递归限制

当您在Python中对较大的输入(> 10^4)执行递归函数时,您可能会遇到“超出最大递归深度错误”。这是在大输入上执行 DFS、阶乘等算法时的常见错误。当您尝试在各种测试用例上运行递归算法时,这在多个平台上的竞争性编程中也很常见。
在本文中,我们将看看为什么会出现这个错误以及如何在Python中处理它。要理解这一点,我们需要先看看尾递归。
尾递归——
在典型的递归函数中,我们通常会先进行递归调用,然后取递归调用的返回值来计算结果。因此,我们只有在所有递归调用都返回一些值之后才能得到最终结果。但是在尾递归函数中,首先执行各种计算和语句,然后对函数进行递归调用。通过这样做,我们将当前步骤的结果传递给函数的下一个递归调用。因此,Tail 递归函数中的最后一条语句是对函数的递归调用。
这意味着当我们对函数执行下一次递归调用时,不再需要当前堆栈帧(被当前函数调用占用)。这使我们能够优化代码。我们只需将当前堆栈帧重用于下一个递归步骤,并对所有其他函数调用重复此过程。
使用常规递归,每个递归调用将另一个条目推入调用堆栈。当函数返回时,它们会从堆栈中弹出。在尾递归的情况下,我们可以对其进行优化,使得函数的所有递归调用只使用一个堆栈条目。这意味着即使在大输入上,也不会出现堆栈溢出。这称为尾递归优化。
lisp 和 c/c++ 等语言有这种优化。但是, Python解释器不执行尾递归优化。因此, Python的递归限制通常设置为一个较小的值(大约 10^4)。这意味着当您向递归函数提供大量输入时,您将收到错误消息。这样做是为了避免堆栈溢出。 Python解释器限制递归限制,以避免无限递归。处理递归限制 -
Python中的“sys”模块提供了一个名为setrecursionlimit()的函数来修改Python中的递归限制。它采用一个参数,即新递归限制的值。默认情况下,该值通常为 10^3。如果您正在处理大输入,则可以将其设置为 10^6,以便可以处理大输入而不会出现任何错误。
例子:
考虑一个使用递归计算数字的阶乘的程序。当输入较大时,程序崩溃并给出“最大递归深度超出错误”。

Python3
# A simple recursive function
# to compute the factorial of a number
def fact(n):
 
    if(n == 0):
        return 1
 
    return n * fact(n - 1)
 
 
if __name__ == '__main__':
 
    # taking input
    f = int(input('Enter the number: \n'))
 
    print(fact(f))


Python3
# importing the sys module
import sys
 
# the setrecursionlimit function is
# used to modify the default recursion
# limit set by python. Using this,
# we can increase the recursion limit
# to satisfy our needs
 
sys.setrecursionlimit(10**6)
 
# a simple recursive function
# to compute the factorial of a number
# it takes one parameter, the
# number whose factorial we
# want to compute and returns
# its factorial
def fact(n):
 
    if(n == 0):
        return 1
 
    return n * fact(n - 1)
 
if __name__ == '__main__':
 
    # taking input
    f = int(input('Enter the number: \n'))
 
    print(fact(f))


输出 :

使用 setrecursionlimit() 方法,我们可以增加递归限制,即使在大输入时程序也可以无错误地执行。

Python3

# importing the sys module
import sys
 
# the setrecursionlimit function is
# used to modify the default recursion
# limit set by python. Using this,
# we can increase the recursion limit
# to satisfy our needs
 
sys.setrecursionlimit(10**6)
 
# a simple recursive function
# to compute the factorial of a number
# it takes one parameter, the
# number whose factorial we
# want to compute and returns
# its factorial
def fact(n):
 
    if(n == 0):
        return 1
 
    return n * fact(n - 1)
 
if __name__ == '__main__':
 
    # taking input
    f = int(input('Enter the number: \n'))
 
    print(fact(f))

输出 :