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

2024-09-28 19:30:17 发布

您现在位置: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()

它在不打印索引的情况下工作,但这是一个要求。如果有人能告诉我我做错了什么,我将不胜感激。谢谢


Tags: middleinputindexreturndefstartlistend
2条回答

您正在使用行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()

在第print(str(selectiona)) + "found at index " + str(index))行中,括号错误,在selectiona后关闭的括号过多。请尝试以下操作:

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

此外,二进制搜索的结果不是您正在打印的结果。你是不是想改做index = binarySearch(lista, selectiona)?你知道吗

相关问题 更多 >