递归函数
1. 递归
(1)什么是递归:在函数中调用自身函数
(2)最大递归深度:默认997/998——是Python从内存角度出发做的限制
n = 0 def story(): global n n+= 1 print(n) story() #997/998 story()
(3)修改最大深度:最好不要改——递归次数太多,则不适合用递归解决问题
import sys sys.setrecursionlimit(2000) #1997/1998
2. 递归的优点
会让代码变简单
3. 递归的缺点
占用内存
4. 能看懂递归
# 算年龄 def age(n): if n == 4: return 40 elif n>0 and n<4: return age(n+1) + 2 print(age(1)) # 学着看递归 ‘‘‘ def age(1): #46 if 1 == 4: return 40 elif 1>0 and 1<4: return age(2) + 2 #44+2 = 46 def age(2): #44 if 2 == 4: return 40 elif 2>0 and 2<4: return age(3) + 2 #42+2 = 44 def age(3): #42 if 3 == 4: return 40 elif 3>0 and 3<4: return age(4) + 2 #40+2 = 42 def age(4): #40 if 4 == 4: return 40 elif 4>0 and 4<4: return age(4+1) + 2 ‘‘‘
5. 应用场景
6. 初识递归
7. 算法——二分查找算法(必须有序排列)
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,82,83,88] def find(l,aim,start = 0,end=None): end = len(l) if end is None else end mid_index = (end - start) // 2 + start #计算中简值 if start <= end: if l[mid_index] < aim: l[mid_index + 1:] return find(l, aim, start=mid_index + 1, end=end) elif l[mid_index] > aim: return find(l, aim, start=start, end=mid_index - 1) else: return mid_index # print(‘找到了‘, mid_index, aim) else: return ‘找不到这个值啊‘ ret1 = find(l,67) ret2 = find(l,64) print(ret1) #找到了 18 print(ret2) #找不到这个值啊
8. 三级菜单——递归实现
原文地址:https://www.cnblogs.com/xc-718/p/9751139.html
时间: 2024-10-17 14:27:18