Python :我应该将 while 循环放在哪里才能使这个二进制搜索代码起作用?
Python : Where should I place the while loop for this Binary search code to work?
所以,我只是处于初学者水平,正在尝试 运行 这个二进制搜索代码。但是我的代码只对列表"only once"进行了划分,给出了答案。我如何让它循环直到找到中点并将索引值作为输出。
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)
您的代码几乎没有错误。您多次获得 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
所以,我只是处于初学者水平,正在尝试 运行 这个二进制搜索代码。但是我的代码只对列表"only once"进行了划分,给出了答案。我如何让它循环直到找到中点并将索引值作为输出。
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)
您的代码几乎没有错误。您多次获得 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