python(day17)二分查找
程序员文章站
2022-03-08 20:12:09
l = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31] def find(l ,aim ,start = 0,end = None): end = len(l) if end is None else end #end的问题解决 mid_index = ( ... ......
l = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31] def find(l ,aim ,start = 0,end = none): end = len(l) if end is none else end #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 '没有找到' #l = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31] ret = find(l,27) print(ret) #注意,是len(l),还有end = end ,start = start,+1-1要注意