测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A43665. 通过二分查找法查找有序列表 [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93] 中的数字位置。当输入的数字不存在于列表中时,输出 FALSE。注:列表的第一个元素是第 0 个。例:输 入:1 输出: 0输入:50 输出: FALSE

填空题 中等

题目描述

通过二分查找法查找有序列表 [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93] 中的数字位置。当输入的数字不存在于列表中时,输出 FALSE。

注:列表的第一个元素是第 0 个。

例:

输 入:1  输出: 0

输入:50 输出: FALSE

参考答案

def BinarySearch(lista, key): min = 0 max = len(lista) - 1 if key in lista: while True: mid = (min + max) / 2 if lista[mid] > key: max = mid - 1 elif lista[mid] < key: min = mid + 1 elif lista[mid] == key: print str(mid) return lista[mid] else: print("FALSE") if __name__ == "__main__": lista= [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93] while True: key = input() BinarySearch(lista, int(key))
上一题 下一题