首页 > 代码库 > Python递归报错:RuntimeError: maximum recursion depth exceeded in comparison

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  5     if n == 0 or n == 1: 6  7         return 1 8  9     else:10 11         return(n * factorial(n - 1))

>>> factorial(989)

...

>>>factorial(990)

...

RuntimeError: maximum recursion depth exceeded in comparison

 

解决方案:

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

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