def binarySearch(list, selection):
start = 0
end = len(list) - 1
while start <= end:
middle = start + (end - start) // 2
middleValue = list[middle]
if middleValue == selection:
return middle
elif selection < middleValue:
end = middle - 1
else:
start = middle + 1
return None
lista = [1, 5, 7, 10, 11, 19,]
print(lista)
selectiona = int(input('Enter a number to search for: '))
index = lista.index(selectiona)
binarySearch(lista, selectiona)
print(str(selectiona)) + "found at index " + str(index))
exit = input()
它无需打印索引即可工作,但这是必需的。如果有人可以建议我做错了什么,我将不胜感激。谢谢
在print(str(selectiona)) + "found at index " + str(index))
行中,您的括号是错误的,在selectiona
之后您关闭了太多。请尝试以下方法:
print(str(selectiona) + "found at index " + str(index))
此外,二进制搜索的结果不是您要打印的结果。您是要改为index = binarySearch(lista, selectiona)
吗?
[您正在使用index
行中的python模块获取index = lista.index(selectiona)
,但没有使用binarySearch
函数提供的输出。
def binarySearch(list, selection):
start = 0
end = len(list) - 1
while start <= end:
middle = start + (end - start) / 2
middleValue = list[middle]
if middleValue == selection:
return middle
elif selection < middleValue:
end = middle - 1
else:
start = middle + 1
return None
lista = [1, 5, 7, 10, 11, 19,]
print(lista)
selectiona = int(input('Enter a number to search for: '))
index = binarySearch(lista, selectiona)
if index:
print(str(selectiona) + " found at index " + str(index))
else:
print(str(selectiona) + " is not there in the list")
exit = input()