python遞歸次數限制

轉載自: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)
View Code

 

當在我本身的機器運行以上代碼時,發現最多能打印到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)
View Code

 

再次運行,順利經過!!!blog

相關文章
相關標籤/搜索