谁能告诉我这个二进制搜索代码在哪里出问题?无法将索引打印给用户

问题描述 投票:1回答:2
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()

它无需打印索引即可工作,但这是必需的。如果有人可以建议我做错了什么,我将不胜感激。谢谢

python algorithm search
2个回答
1
投票

print(str(selectiona)) + "found at index " + str(index))行中,您的括号是错误的,在selectiona之后您关闭了太多。请尝试以下方法:

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

此外,二进制搜索的结果不是您要打印的结果。您是要改为index = binarySearch(lista, selectiona)吗?


1
投票

[您正在使用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()
© www.soinside.com 2019 - 2024. All rights reserved.