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()
它在不打印索引的情况下工作,但这是一个要求。如果有人能告诉我我做错了什么,我将不胜感激。谢谢
您正在使用行
index = lista.index(selectiona)
中的python模块获取index
,而没有使用binarySearch
函数提供的输出。你知道吗在第
print(str(selectiona)) + "found at index " + str(index))
行中,括号错误,在selectiona
后关闭的括号过多。请尝试以下操作:print(str(selectiona) + "found at index " + str(index))
此外,二进制搜索的结果不是您正在打印的结果。你是不是想改做
index = binarySearch(lista, selectiona)
?你知道吗相关问题 更多 >
编程相关推荐