python(day17)二分查詢
阿新 • • 發佈:2018-11-07
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: returnfind(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要注意