有人可以帮助我如何访问所有浮点值并进行二进制搜索,以便如果匹配将输出标题,该标题是列表中的第二个。例如,看下面的输出是否匹配0.369,它将输出自私的。谢谢。
到目前为止,列表的输出是此[['0.369','selfish','Future'] ['0.412','family','Future']],该列表是根据从最低到最大都存储在存储中= []
如果我能正确理解您的要求,这就是您想要的:
def binary_search(storage, target):
first = 0
last = len(storage) - 1
while first <= last:
mid = (first + last) // 2
value = float(storage[mid][0])
if target == value:
return storage[mid][1]
elif value < target:
first = mid + 1
else:
last = mid - 1
return -1
storage = [["0.369", "selfish", "Future"], ["0.412", "family", "Future"]]
target = float(input("Please enter the desired float "))
result = binary_search(storage, target)
print(result)
请确保您添加数据验证。例如,如果用户输入无效值“ abc”会发生什么?