【问题标题】:Python : Where should I place the while loop for this Binary search code to work?Python:我应该在哪里放置这个二进制搜索代码的while循环?
【发布时间】:2017-05-13 11:46:17
【问题描述】:

所以,我只是处于初学者级别并尝试运行此二进制搜索代码。但是我的代码只将列表“只划分一次”并给出了答案。如何让它循环直到找到中点并将索引值作为输出。

user_input = (int(input("Enter a number you want to find : ")))

lister = [i for i in range(1,100)]






def bi_search(a,user):
  low = 0
  high = len(a)
  mid = int(low + (high-low)/2)
  while True:
    if user < a[mid]:
      low = 0
      high = mid-1
      mid = int(low + (high-low)/2)
      print("Your number is in left half")
      print("Your number is",mid,"thelement in the list")
      break      
    elif user > a[mid]:
      low= mid+1
      high = len(a)
      mid = int(low + (high-low)/2)
      print("Your number is in right half")
      print("Your number is",mid,"th element in the list")
      break      

bi_search(lister,user_input)

【问题讨论】:

  • while循环中的逻辑不正确,只需要保留high = mid-1low= mid+1这两行即可。

标签: python algorithm python-2.7 python-3.x binary-search


【解决方案1】:

您的代码几乎没有错误。您多次获得mid 并且也很少出现其他错误。我已经编辑了您的bi_search,并在下面提供。

代码:

def bi_search(a,user):
        low = 0
        high = len(a)
        while low <= high:   
            mid = low + (high - low) // 2
            val = a[mid]
            if user == val:
                return mid
            elif user > val:
                low = mid+1
            elif user < val:
                high = mid-1

【讨论】:

  • 谢谢比拉。这真的很有帮助。
最近更新 更多