我需要编写代码的帮助,该代码使用二进制搜索来检查排序的列表并输出最接近用户给定目标值的代码,并输出列表中的第一件事。例如,使用下面的输出将输出自私]
到目前为止,列表的输出是这个[['Selfish','0.369','Future'] ['Xanny Family','0.412','Future']]该列表根据十进制值(从最低到最大)进行排序,它们全部存储在存储中= []
所以这就是我想做的
target = input(float("Please enter the desired float "))
def binary_search(storage[1], target):
first = 0
last = len(storage[1]) - 1
while first <= last:
mid = (first+last) // 2
if target == storge[1][mid][0]:
return storage[1][mid][1]
elif storage[1][mid][0] < target:
first = mid + 1
else:
last = mid - 1
return -1
请帮助。...
如果我能正确理解您的要求,这就是您想要的:
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”会发生什么?