当我尝试使用二进制搜索功能查找列表开头或结尾的数字时,我的函数无法正确输出结果。我该如何解决?
我尝试使用我的函数搜索b = 1和b =562。对于这两种情况,我的函数输出“ {}都没有在列表中”。
# initialize values
a = [1, 3, 5, 6, 7, 8, 12, 56, 78, 234, 562]
b = 562
head = 0
tail = len(a) - 1
# binary search method
def binary_search(a, b, head, tail):
mid = int(len(a) / 2)
if b == a[mid]:
print("{} is found in the list".format(b))
# this is where I need HELP
elif len(a) == 1 or len(a) == 2 or len(a) == 3:
if b == head or b == tail or b == mid:
print("{} is found in the list".format(b))
else:
print("{} is not found in the list".format(b))
# this is all GOOD
elif b > a[mid]:
a = a[mid:tail]
binary_search(a, b, head, tail)
elif b < a[mid]:
a = a[head:mid]
binary_search(a, b, head, tail)
binary_search(a, b, head, tail)
我希望函数输出“ {}在列表中”
答案 0 :(得分:0)
这是尴尬的代码。考虑一下为什么对照这些值中的每一个进行检查,并尝试简化逻辑。
elif len(a) == 1 or len(a) == 2 or len(a) == 3:
if b == head or b == tail or b == mid:
print("{} is found in the list".format(b))
else:
print("{} is not found in the list".format(b))
例如:
elif len(a) <= 3:
if b in [head, mid, tail]:
...至少更容易阅读。
您的逻辑错误在这里:
if b == head or b == tail or b == mid:
b
是目标值; head, tail, mid
是列表的索引。由于列表中只有11个项目,因此它们都不等于562。请尝试:
if b == a[head] ...
答案 1 :(得分:0)
首先
b == head or b == tail or b == mid
将您要查找的值与列表的索引进行比较
第二
binary_search(a, b, head, tail)
假定头和尾保持不变,但是您只是在上一条语句中划分了列表
a = a[mid:tail]
所以头总是0,尾总是len(a)-1
第三 由于您的代码取决于将列表划分为3个或更小的长度,因此,在达到3个或更小的长度之前,应先处理b = a [mid]的情况
因此,您应该先确定条件
elif b >= a[mid]:
最后
a = a[mid:tail]
因为tail指的是您要排除的最后一个元素的索引,因为在数组切片中,结尾应等于您希望+1的最后一个元素的索引
更正的代码:
# initialize values
a = [1, 3, 5, 6, 7, 8, 12, 56, 78, 234, 562]
b = 1
head = 0
tail = len(a) - 1
# binary search method
def binary_search(a, b, head, tail):
print(head,tail)
mid = int(len(a) / 2)
if b == a[mid]:
print("{} is found in the list".format(b))
# this is where I need HELP
elif len(a) == 1 or len(a) == 2 or len(a) == 3:
if b == a[head] or b == a[tail] or b == a[mid]:
print("{} is found in the list".format(b))
else:
print("{} is not found in the list".format(b))
# this is all GOOD
elif b >= a[mid]:
a = a[mid:tail+1]
binary_search(a, b, 0, len(a)-1)
elif b < a[mid]:
a = a[head:mid]
binary_search(a, b, 0, len(a)-1)
binary_search(a, b, head, tail)
答案 2 :(得分:0)
首先,您在这里遇到问题:
a = a[mid:tail]
在这种情况下,将不包含tail
元素。另外,您还不需要包含mid
元素,因为您已经选中了它。因此,此行应更改为:
a = a[mid+1:tail+1]
第二,正如贾森哈珀在评论中提到的那样,您在这里遇到了问题:
elif len(a) == 1 or len(a) == 2 or len(a) == 3:
if b == head or b == tail or b == mid:
您正在与索引进行比较,而您应该对元素进行比较。第一行也可以优化:
elif len(a) <= 3:
if b == a[head] or b == a[tail] or b == a[mid]: