所以,我只是在初学者级别,并试图运行这个二进制搜索代码。但是我的代码只将列表“仅限一次”并给出答案。如何使其循环直到找到中点并将索引值作为输出。
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)
答案 0 :(得分:0)
您的代码几乎没有错误。您已经多次获得echo
次,也很少有其他错误。我已经编辑了您的bi_search,并在下面提供。
代码:
mid