Python 遞迴 次數限制
實際應用中遇到了一個python遞迴呼叫的問題,報錯如下:
RuntimeError: maximum recursion depth exceeded while calling a Python object
網上找了一下,原來Python確實有遞迴次數限制,預設最大次數為1000
在正常的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.
那麼如何進行判斷處理呢?下面給出兩段程式碼,供參考。
程式碼如下:
def recursion(n): if(n <= 0): return print n recursion(n - 1) if __name__ == "__main__": recursion(1000)
當在我自己的機器執行以上程式碼時,發現最多能列印到998,然後就會丟擲 “RuntimeError: maximum recursion depth exceeded” 的錯誤了。 嘿,還真有限制。但轉念一想,python不會這麼弱吧。經過一番查詢,發現這是python專門設定的一種機制用來防止無限遞迴造成Python溢位崩潰, 最大遞迴次數是可以重新調整的。 (
import sys sys.setrecursionlimit(1500) # set the maximum depth as 1500 def recursion(n): if(n <= 0): return print n recursion(n - 1) if __name__ == "__main__": recursion(1200)
再次執行,順利通過!!!