[英]Different binary search outputs even though the list stays about the same
I'm new to python and trying to understand binary searching.我是 python 的新手,并试图理解二进制搜索。 I wrote a code in which inventory is an array of 5 elements and input a particular item and then search the item using the binary search technique.
我编写了一个代码,其中库存是一个由 5 个元素组成的数组并输入一个特定项目,然后使用二进制搜索技术搜索该项目。 This is my code:
这是我的代码:
inventory=["10", "50", "100", "150", "200"]
SearchItem=input("Enter item: ")
LB=0
UB=len(inventory)-1
Found=False
while Found==False and LB <= UB:
Mid=(LB + UB)//2
if inventory[Mid]==SearchItem:
print("Item found in the position: ", Mid + 1)
Found=True
elif SearchItem>inventory[Mid]:
LB= Mid + 1
else:
UB= Mid - 1
if Found==False:
print("Item doesn't exist.")
What's the need for -1
in len(inventory)-1
? len(inventory)-1
-1
的 -1 需要什么? I was trying to find out what the -1 meant here but am coming across more complicated codes.我试图找出 -1 在这里的含义,但遇到了更复杂的代码。
How does SearchItem
know if SearchItem
is > or < inventory[Mid]
? SearchItem
如何知道SearchItem
是 > 还是 < inventory[Mid]
? Cause if it does, shouldn't it be automatically known by inventory[Mid]
where SearchItem
is at?因为如果是这样,它不应该被
SearchItem
所在的inventory[Mid]
自动知道吗? I also tried adding both integers and strings to the inventory as:我还尝试将整数和字符串添加到清单中:
inventory=["a", "10", "50", "100", "200"]
and:和:
inventory=["10", "50", "100", "200", "a"]
but it comes with the following outputs respectively:但它分别带有以下输出:
Enter item: a
Item found in the position: 5
. .
Enter item: a
Item doesn't exist.
Why do these two inventories have different outputs?为什么这两个库存有不同的输出? Cause if
inventory[Mid]
knows where SearchItem
lies, shouldn't the position of a
be found?因为如果
inventory[Mid]
知道SearchItem
所在的位置,不应该找到a
的position 吗?
I do not know the answer to the question -1 of the length (it makes no sense) And the error that caused the code to not work was that you stored numbers in the array as strings Because of this, python compared values not as numbers, but as words (in lexicographic order) If you remove the quotes in the array declaration and add int() in the input line, then the code starts working as it should我不知道长度问题 -1 的答案(这没有意义)导致代码不起作用的错误是您将数组中的数字存储为字符串因此,python 比较的值不是数字,但作为单词(按字典顺序)如果删除数组声明中的引号并在输入行中添加 int(),则代码开始正常工作
Corrected code:更正的代码:
inventory = [10, 50, 100, 150, 200]
SearchItem = int(input("Enter item: "))
LB = 0
UB = len(inventory)
Found = False
while Found == False and LB <= UB:
Mid = (LB + UB) // 2
if inventory[Mid] == SearchItem:
print("Item found in the position: ", Mid + 1)
Found = True
elif SearchItem > inventory[Mid]:
LB = Mid + 1
else:
UB = Mid - 1
if Found == False:
print("Item doesn't exist.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.