转载自:http://www.cnblogs.com/wozijisun/p/5642540.htmlhtml
实际应用中遇到了一个python递归调用的问题,报错以下:python
RuntimeError: maximum recursion depth exceeded while calling a Python objectide
网上找了一下,原来Python确实有递归次数限制,默认最大次数为1000ui
在正常的python里:
In [1]: sys.setrecursionlimit?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function setrecursionlimit>
Namespace: Interactive
Docstring:
setrecursionlimit(n)
Set the maximum depth of the Python interpreter stack to
n. This limit prevents infinite recursion from causing an
overflow of the C stack and crashing Python. The highest
possible limit is platform-dependent. spa
那么如何进行判断处理呢?下面给出两段代码,供参考。code
代码以下:orm
1 def recursion(n): 2 if(n <= 0): 3 return 4 print n 5 recursion(n - 1) 6 7 if __name__ == "__main__": 8 recursion(1000)
当在我本身的机器运行以上代码时,发现最多能打印到998,而后就会抛出 “RuntimeError: maximum recursion depth exceeded” 的错误了。 嘿,还真有限制。但转念一想,python不会这么弱吧。通过一番查找,发现这是python专门设置的一种机制用来防止无限递归形成Python溢出崩溃, 最大递归次数是能够从新调整的。 (http://docs.python.org/2/library/sys.html#sys.setrecursionlimit),修改代码以下:htm
1 import sys 2 sys.setrecursionlimit(1500) # set the maximum depth as 1500 3 4 def recursion(n): 5 if(n <= 0): 6 return 7 print n 8 recursion(n - 1) 9 10 if __name__ == "__main__": 11 recursion(1200)
再次运行,顺利经过!!!blog