Python中递归的最大次数
2016-07-05 10:02
676 查看
实际应用中遇到了一个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溢出崩溃, 最大递归次数是可以重新调整的。 (http://docs.python.org/2/library/sys.html#sys.setrecursionlimit),修改代码如下:
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)
再次运行,顺利通过!!!
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溢出崩溃, 最大递归次数是可以重新调整的。 (http://docs.python.org/2/library/sys.html#sys.setrecursionlimit),修改代码如下:
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)
再次运行,顺利通过!!!
相关文章推荐
- Python-定时器使用
- python 9种部署方法
- class2_week6b
- Python实现插件机制——自动import一个目录下的所有.py文件
- 8.01 python底层代码设计去冗余,编写便于理解的函数
- python转exe的小工具
- Python冒泡排序
- 新浪SAE上配置WeRoBot微信机器人,python,Mac环境
- Python股票历史数据下载
- python os.path模块
- Python安装Mysql驱动出错解决(最新出炉)
- Python中PyQuery库的使用总结
- The Zen of Python, by Tim Peters
- python 安装 twisted 库
- python 关于pylab的安装
- Python的shutil模块中文件的复制操作函数详解
- 简单掌握Python中glob模块查找文件路径的用法
- 详解Python中的array数组模块相关使用
- Python中shutil模块的常用文件操作函数用法示例
- [python] python 安装mysql-python时,mysql_config not f