python - 谁能告诉我这个二进制搜索代码哪里出错了?无法向用户打印索引
问题描述
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)
代替吗?
推荐阅读
- php - Laravel store() 方法不会提交数据
- php - PHP在本地主机上工作,在谷歌云服务器上出错
- python - 从 bash 运行 tensorflow_model_server 会引发“找不到命令错误”
- php - 替代图像文本中的多个字符串
- android - 在 Android Studio 中使用 Recycler View 单击分页中的每个项目?
- android - 如何用android“dp”测量位图
- java - 更改 Java 中公共变量的值,供多个框架使用
- jupyter-notebook - 由于类型错误,通过标签删除某些单元格失败
- python - 改变熊猫的nan值
- jenkins - 使用 jenkins 更新 kubernetes 部署