递归函数
递归 : 在函数中调用自身函数
最大递归深度默认是997/998 —— 是python从内存角度出发做得限制
实现程序:
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def find(l,aim):
mid_index = len(l) // 2
if l[mid_index] == aim:
print('找到啦,位置是:',mid_index)
elif l[mid_index] < aim:
new_l = l[mid_index + 1:]
find(new_l,aim)
elif l[mid_index] > aim:
new_l = l[:mid_index]
find(new_l, aim)
else:
print('找不到')
find(l,22)
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def find(l,aim,start = 0,end = None):
end = len(l) if end is None else end # end = len(l) 24
mid_index = (end - start)//2 + start #计算中间值 12 + 0 = 12
if l[mid_index] < aim: #l[12] < 44 #41 < 44
find(l,aim,start =mid_index+1,end=end) # find(l,44,start=13,end=24)
elif l[mid_index] > aim:
find(l, aim, start=start, end=mid_index-1)
else:
print('找到了',mid_index,aim)
老师给出的最终版:(解决了以上所有问题,但是一旦输入的aim超过了列表最大的值(这里是最大值是88),就会报错,原因是列表溢出,就是mid_index会超过l的最大长度(这里最大长度是25),而l[mid_index]就会报错
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,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:
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
else:
return '找不到这个值'
find(l,22)
最最最最最终版:
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,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 mid_index < len(l):
if start <= end:
if l[mid_index] < aim:
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
else:
return '找不到这个值'
else:
return '找不到这个值'
print(find(l,100))