gpt4 book ai didi

python-3.x - 在我的二进制搜索算法中,Python 在列表中找不到 0 个索引成员

转载 作者:行者123 更新时间:2023-12-04 10:46:22 25 4
gpt4 key购买 nike

我该如何修复代码 - 算法会为所有情况找到搜索到的数字,除非您尝试找到 0 索引号或在我的情况下 search_num = 1。

list1 = [1, 3, 4, 5, 19, 21, 52, 100, 152]
search_num = 1

def binarySearch(array, number):

lower_b_index = 0
upper_b_index = len(array) - 1

while lower_b_index <= upper_b_index:

mid_point = (lower_b_index + upper_b_index) // 2

if array[mid_point] == number:
return mid_point
elif array[lower_b_index] == number:
return lower_b_index
else:
if array[mid_point] < number:
lower_b_index = mid_point + 1
else:
upper_b_index = mid_point - 1

return False

a1 = binarySearch(list1, search_num)

if a1:
print("The searched position: ", a1 + 1)
else:
print("Not Found!")

最佳答案

您的问题不在您的 binarySearch算法是你的 if后声明。

你算法返回 a1 = 0这是正确的,您的检查 if 0 0 是 bool 值到 False

一个简单的修复方法是 return None并检查 if a1 is not None

list1 = [1, 3, 4, 5, 19, 21, 52, 100, 152]
search_num = 1

def binarySearch(array, number):

lower_b_index = 0
upper_b_index = len(array) - 1

while lower_b_index <= upper_b_index:

mid_point = (lower_b_index + upper_b_index) // 2

if array[mid_point] == number:
return mid_point
elif array[lower_b_index] == number:
return lower_b_index
else:
if array[mid_point] < number:
lower_b_index = mid_point + 1
else:
upper_b_index = mid_point - 1

return None # Change here

a1 = binarySearch(list1, search_num)

if a1 is not None: # Change here
print("The searched position: ", a1 + 1)
else:
print("Not Found!")

关于python-3.x - 在我的二进制搜索算法中,Python 在列表中找不到 0 个索引成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com