【问题标题】:Can anyone please advise me where I'm going wrong with this binary search code? Unable to print index to user谁能告诉我这个二进制搜索代码哪里出错了?无法向用户打印索引
【发布时间】:2019-11-14 13:15:28
【问题描述】:
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


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回复!我仍然很业余,所以我无法完全理解为什么存储索引需要传递带参数的函数而不仅仅是列表,这在程序中不会改变。
  • @scopuli1 我不确定我是否正确理解了您的后续问题。当您编写def binarySearch(list, selection): 时,您将binarySearch 定义为需要两个参数listselection 的函数。当您使用 binarySearch(lista, selectiona) 调用此函数时,您提供 listaselectiona 作为运行此函数的具体参数。该函数返回找到的位置,并通过在调用前加上index = ,我们将此结果存储在变量index中,以便稍后打印。
【解决方案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()

【讨论】:

  • 旁注: middle = (start + end) // 2 可以在 Python 中安全地完成。
  • 感谢您抽出宝贵时间回复。令我惊讶的是,有人可以在几分钟内破解此代码,而我已经坚持了好几个小时!我从来没有想过如果没有找到价值,我需要考虑。我能问一下,为什么需要传递带有参数的函数来查找索引,而不仅仅是列表?
  • 如果你只是将列表作为参数传递,函数不知道在该列表中搜索哪个数字,因此它需要它需要搜索的数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2015-07-28
  • 2016-11-10
相关资源
最近更新 更多