Python递归报错:RuntimeError: maximum recursion depth exceeded in comparison

Python中默认的最大递归深度是989,当尝试递归第990时便出现递归深度超限的错误:

RuntimeError: maximum recursion depth exceeded in comparison

简单方法是使用阶乘重现:

1 #!/usr/bin/env Python
2 
3 def factorial(n):
4     if n == 0 or n == 1:
5         return 1
6     else:
7         return(n * factorial(n - 1))    

>>> factorial(989)

...

>>>factorial(990)

...

RuntimeError: maximum recursion depth exceeded in comparison

解决方案:

可以手动设置递归调用深度:

>>> import sys
>>> sys.setrecursionlimit(10000000)

原文地址:https://www.cnblogs.com/Zhanxueyou/p/3799410.html