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)
