解决python递归函数及递归次数受到限制的问题
作者:LLLLLLLLLLLLIU 时间:2023-12-01 01:49:35
递归函数及递归次数受到限制
一个函数在内部调用自己,那么这个函数是递归函数。递归会反复使用本身,每递归一次,越接近最终的值。当一个问题可以由许多相似的小问题解决, 可以考虑使用递归函数。随着递归的深入,问题规模相比上次都应所减小。return函数本身的方法保证了递归的持续进行,但是如果没有明确的结束条件,递归会无限进行下去。所以当已经到了问题解决的程度, 应该告诉函数结束递归,这就需要明确的结束条件。
常见的两个递归例子:求和、求阶乘n!
求和:sum=n+n(n-1)+…+1
def sum(n):
if n > 0:
return n+sum(n-1)
else:
return 0
new_sum = sum(10)
print(new_sum)
#output
55
求阶乘:n!=1x2x3…xn
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
new_sum = factorial(5)
print(new_sum)
#output
120
使用递归函数需要注意递归次数默认限制为1000,如果递归次数较多会导致栈溢出的问题
比如
def sum(n):
if n > 0:
return 1+sum(n-1)
else:
return 0
new_sum = sum(1000)
print(new_sum)
会报RecursionError: maximum recursion depth exceeded in comparison的错误
解决问题的办法是修改可递归的次数
import sys
sys.setrecursionlimit(1500)#可递归次数修改为1500
def sum(n):
if n > 0:
return 1+sum(n-1)
else:
return 0
new_sum = sum(1000)
print(new_sum)
#output
1000
修改递归次数时需要注意,修改可递归次数为1500,递归深度到不了1500,在1400左右。默认可递归次数为1000,递归深度也到不了1000,到992左右
如何控制递归的次数
经常会用到递归,虽然能解决很多问题,但其缺点很明显,有可能无法跳出造成死循环,能控制递归次数就可以避免这种情况。
用lua尝试了几种方法,
第一种
在方法内定义一个变量计数:
function recursionTest()
local times = 0
if times < 10 then
times = times + 1
recursionTest()
end
if times == 0 then
print("outer round")
end
end
执行下来,是无法限制的,因为局部变量每次都会重置为0。
第二种
local recurTimes = 0
function recursionTest2()
if recurTimes < 10 then
recurTimes = recurTimes + 1
recursionTest2()
end
end
这种方法可以控制次数,但是变量需要定义在方法体外,执行函数前都需要先把这个变量设为0,需要在递归方法外包一层,比较繁琐。
第三种
function recursion(str, t)
str = str or "first time "
t = t or 0
t = t + 1
print(str, t)
if t < 10 then
recursion("times:", t)
end
if t == 1 then
print("outer round")
end
end
在递归时传入一个自增变量,达到阈值时停止递归,执行最外层时无需传参,默认值为0,且可根据t的值判断当前的递归层数,可以在递归结束时,在最外层执行完之前做其他事情,一举两得。
来源:https://blog.csdn.net/weixin_44851971/article/details/106678010
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
5个Python杀手级的自动化脚本分享
Python如何通过手肘法实现k_means聚类详解
![](https://img.aspxhome.com/file/2023/4/127724_0s.png)
TensorFlow自定义损失函数来预测商品销售量
![](https://img.aspxhome.com/file/2023/4/101424_0s.png)
Layui 带多选框表格监听事件以及按钮自动点击写法实例
如何有效防止sql注入的方法
![](https://img.aspxhome.com/file/2023/4/116324_0s.png)
正则给header的冒号两边参数添加单引号(Python请求用)
![](https://img.aspxhome.com/file/2023/4/110004_0s.png)
ASP在线转flv+缩略图
python字典操作实例详解
4行Python代码生成图像验证码(2种)
![](https://img.aspxhome.com/file/2023/9/76909_0s.png)
Python hashlib模块详细讲解使用方法
pytest中文文档之编写断言
django反向解析URL和URL命名空间的方法
在pandas中一次性删除dataframe的多个列方法
Python使用PyCrypto实现AES加密功能示例
Requests库实现数据抓取与处理功能
Python Pyinstaller库安装步骤以及使用方法
![](https://img.aspxhome.com/file/2023/6/133436_0s.png)
Web 开发中遇到的UTF-8编码的问题总结第1/2页
Python unittest单元测试框架及断言方法
![](https://img.aspxhome.com/file/2023/5/79785_0s.png)
Python实现的本地文件搜索功能示例【测试可用】
![](https://img.aspxhome.com/file/2023/2/111942_0s.png)