简体   繁体   English

Python,IDLE:太多的递归错误

[英]Python, IDLE: Too many recursive errors

This is supposedly a problem with the IDLE editor for Python. 据说这是Python的IDLE编辑器的问题。 (I'm running Python 3.3.0 on OSX, but the same problem occurs with 2.7.3) (我在OSX上运行Python 3.3.0,但是在2.7.3中会发生相同的问题)

I'm using IDLE to write Python programs. 我正在使用IDLE编写Python程序。 My problem is: Calling a recursive function, which calls itself too many times (1000 times), doesn't give me a single runtime error, but rather, it keeps sending me error messages until I close the program. 我的问题是:调用一个自身调用过多次(1000次)的递归函数不会给我一个运行时错误,而是在关闭程序之前一直向我发送错误消息。

The error which it should be sending is: "RuntimeError: maximum recursion depth exceeded." 它应该发送的错误是:“ RuntimeError:超过最大递归深度。” The error which it sends a thousand times isntead is simply a point out to where in the script the problem is: 它发送一千次istead的错误只是指出问题所在的位置:

Traceback (most recent call last):
  File "<pyshell#112>", line 1, in <module>
    factorial(1.5)
  File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial
    recurse = factorial(n-1)
  File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial
    recurse = factorial(n-1)

etc. 等等

This goes with all recursive functions calling itself too many times, but the specific function used here is: 这与所有递归函数多次调用自身有关,但此处使用的特定函数是:

def factorial(n):
    if n == 0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result

To stop python from showing those hundreds of errors, you can use a try-except block: 要阻止python显示这数百个错误,可以使用try-except块:

def factorial(n):
    if n == 0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result
try:
    print (factorial(6000))
except RuntimeError as e:
    print (e)

output: 输出:

#print factorial(1000)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

#print factorial(6000)
maximum recursion depth exceeded in comparison

In your case this error occurs because python has a limit on the maximum recursion depth,it is there to stop the C stack from overflow. 在您的情况下,由于python对最大递归深度有限制,因此会发生此错误,它可以阻止C堆栈溢出。 But you can change it using sys.setrecursionlimit : 但是您可以使用sys.setrecursionlimit更改它:

In [4]: import sys

In [5]: sys.getrecursionlimit()
Out[5]: 1000

Problem is that you are trying to use a float and the code does not handle that. 问题是您尝试使用浮点数,而代码无法处理该浮点数。 So, 1.5 -1 becomes 0.5, which causes the first recursive call. 因此,1.5 -1变为0.5,这将导致第一个递归调用。 Then, 0.5 -1 becomes -0.5, which causes the further recursive calls. 然后,0.5 -1变为-0.5,这导致进一步的递归调用。

Just in order to handle that, use:- 为了解决这个问题,请使用:-

if n<=0: return 1 如果n <= 0:返回1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM