谁能告诉我这个二进制搜索代码哪里出错了?无法向用户打印索引


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 = lista.index(selectiona)行中的python模块获取index,而不是使用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()

相关内容

  • 没有找到相关文章

最新更新