# 来复习一下二分法
# 第一种方法: 递归
def eropen(l,num):
m = len(l) // 2
if m > 0:
if l[m] > num:
eropen(l[:m],num)
elif l[m] < num:
eropen(l[m+1:], num)
else:
print(你找的数字在列表中)
else:
print(你找的数字不在列表中)
l = [1, 3, 4, 6, 7, 8, 9, 11, 15, 17, 19, 21, 22, 25, 29, 33, 38, 69,99,107]
print(eropen(l,22))
# 第二种方法(while else 用法)
def perform_open(l,num):
'''
:param l: 有序的列表
:return:
'''
low = 0
high = len(l)-1
while low <= high:
middle = (low+high) // 2
if l[middle] > num:
high = middle - 1
elif l[middle] < num:
low = middle + 1
else:
print("你要找是值为{},在列表中的第{}位".format(l[middle],middle))
break
else:
print("你找的数字不在列表中")
l = [1, 3, 4, 6, 7, 8, 9, 11,15, 17, 19, 21, 22, 25, 29, 33, 38, 69,99,107]
perform_open(l,15)
网友评论