list 拓展 二分法 创建一个函数查找

#  二分查找
l01 = [i for i in range(1,101)] start_index = 0 end_index = len(l01)-1 while start_index <= end_index: mid_index = (start_index + end_index) // 2 if l01[mid_index] == 77: print('找到了') break elif l01[mid_index] > 77: end_index = mid_index - 1 else: start_index = mid_index + 1 else: print('没找到') # 找到了 # binarysearch 创建一个函数 查找 是否存在 def binarysearch(l01,num): start_index = 0 end_index = len(l01) - 1 while start_index <= end_index: mid_index = (start_index + end_index) // 2 if l01[mid_index] == num: return mid_index elif l01[mid_index] > num: end_index = mid_index - 1 else: start_index = mid_index + 1 return -1 print(binarysearch([1,2,3,5,4,5,6,9,84,5,2,5,874,5,5],84)) # -1 # 寻找中间数是否对应 对应输出 84 不对应输出-1

 

posted @ 2020-07-09 20:46  XuanchenLi  阅读(128)  评论(0编辑  收藏  举报