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

问题描述

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()

它可以在不打印索引的情况下工作,但这是一项要求。如果有人可以就我做错的事情提出建议,我将不胜感激。谢谢

标签: pythonalgorithmsearch

解决方案


print(str(selectiona)) + "found at index " + str(index))您的括号错误的行中,您在 . 之后关闭了太多selectiona。试试这个:

print(str(selectiona) + "found at index " + str(index))

此外,二进制搜索的结果不是您要打印的结果。你的意思是index = binarySearch(lista, selectiona)代替吗?


推荐阅读