Python中递归的最大次数
生活随笔
收集整理的這篇文章主要介紹了
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.那么如何進行判斷處理呢?下面給出兩段代碼,供參考。
代碼如下:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' 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溢出崩潰, 最大遞歸次數是可以重新調整的。 (http://docs.python.org/2/library/sys.html#sys.setrecursionlimit),修改代碼如下:
import sys sys.setrecursionlimit(1500) # set the maximum depth as 1500def recursion(n): if(n <= 0): return print n recursion(n - 1) if __name__ == "__main__":recursion(1200)再次運行,順利通過!!!
總結
以上是生活随笔為你收集整理的Python中递归的最大次数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Python解压zip、rar文件
- 下一篇: Python:为什么只有一个元素的tup