Python 最大递归,关于 sys.setrecursionlimit() 的问题 [英] Python max recursion, question about sys.setrecursionlimit()

查看:33
本文介绍了Python 最大递归,关于 sys.setrecursionlimit() 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 sys.setrecursionlimit()

I have one question about sys.setrecursionlimit()

来自 python docs 这个函数:
将 Python 解释器堆栈的最大深度设置为 limit.此限制可防止无限递归导致 C 堆栈溢出和 Python 崩溃.可能的最高限制取决于平台.当用户有需要深度递归的程序和支持更高限制的平台时,她可能需要将限制设置得更高.这应该小心完成,因为过高的限制会导致崩溃.

From the python docs this function:
Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care because a too-high limit can lead to a crash.

让我们用这个无用的递归函数:

Let's take this useless recursive function:

def rec(N):
     if N==0:
         return 1
     else:
         return rec(N-1);

现在让我们将最大递归设置为 100:

Now let's set the max recursion to 100:

sys.setrecursionlimit(100)

如果我尝试 rec(99)(100 次递归调用),我得到:

If I try rec(99) (100 recursive calls), I get:

RuntimeError: maximum recursion depth exceeded

要计算 rec(99),我需要将递归限制设置为 105.

To calculate rec(99) I need to set recursion limit to 105.

为什么会这样?

推荐答案

它的名字很糟糕.它应该说堆栈深度,而不是递归深度.递归意味着它一遍又一遍地限制同一个线程.实际上,您可以拥有只有 100 次调用深度的实际代码.我不会推荐它,但你可以.他们可以侥幸逃脱,因为在实际世界中,您遇到这种情况的唯一时间是递归.当您因此而崩溃时,看到递归"这个词可以让您立即了解要查找的内容,而不是堆栈".

It's poorly named. It should say Stack Depth, not Recursion depth. Recursion implies it's the same thread over and over again that it's limiting. In reality, you could have actual code that just has calls 100 deep. I wouldn't recommend it, but you could. They can get away with it because in the practical world, the only times you ever run into this scenario is with recursion. When you crash because of this, seeing the word "Recursion" gives you an immediate clue of what to look for as opposed to "Stack".

(堆栈应该给任何体面的程序员同样的线索,但老实说,你的代码刚刚崩溃,你想要一个相关的错误消息,对吧?99.99999% 的时间这会告诉你你搞砸了什么(你错过了递归的基本情况.))

(Stack should give any decent programmer the same clue, but let's be honest, your code just crashed and you want a relevant error message, right? 99.99999% of the time this tells you exactly what you messed up (you missed your base case for recursion.))

这篇关于Python 最大递归,关于 sys.setrecursionlimit() 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆