Python:我应该在哪里放置这个二进制搜索代码的while循环?

时间:2017-05-13 03:06:38

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

所以,我只是在初学者级别,并试图运行这个二进制搜索代码。但是我的代码只将列表“仅限一次”并给出答案。如何使其循环直到找到中点并将索引值作为输出。

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)

1 个答案:

答案 0 :(得分:0)

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

代码:

mid