线性搜索不会继续到数组结尾

时间:2018-08-24 10:46:23

标签: python-3.x

该程序用于显示所有数字71的位置(使用计数器)。它只会在停止之前找到第一个数字。

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
search_value = 71
counter = 0
found = False

while found == False and not counter == len(numbers):
    if numbers[counter] == search_value:
        found = True
    else:
        counter = counter + 1
if found == True:
   print("Found at position ",counter)
else:
   print("No match found")

python版本是3.7.0

3 个答案:

答案 0 :(得分:0)

您的程序在找到第一个71之后停止,因为此时found的值将更改为True,这反过来将导致and运算符的一侧为Falsefound == False),因此整个条件将为False,因为'and'运算符要求双方都为True才能得出True。 / p>

您可以通过以下方式完成您想做的事情:

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
search_value = 71
counter = 0
found = False


while counter < len(numbers): #if counter is equal to/more than the length we'll be outside the list range
    if numbers[counter] == search_value:
        print("Found at position ",counter)
        found = True
        counter += 1 #Same as counter = counter + 1
    else:
        counter += 1
if not found: #Same as asking whether found is False
   print("No match found")

答案 1 :(得分:0)

这样做的原因是您的while循环仅在found = False时运行。

如果我正确理解了您的问题,则希望为每次出现的counter找到每个索引(search_value)。

要实现此目的,您可以使用for循环遍历列表。因此,结果代码将是:

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
search_value = 71
found = False

for counter in range(len(numbers)):
    if numbers[counter] == search_value:
        found = True 
        print("Found at position ",counter)

if not found:
   print("No match found")

如果您不想每次找到该值时都单独输入一条消息,也可以更改上面的代码。

可能看起来像这样:

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
search_value = 71
found_indexes = []

for counter in range(len(numbers)):
    if numbers[counter] == search_value:
        found_indexes.append(counter)

if len(found_indexes) == 0:
   print("No match found")
else:
   print("Found at positions: ", found_indexes)

答案 2 :(得分:0)

使用此工具可以正常工作,谢谢大家的答复

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
search_value = 71
found = False

while found == False:
     for counter in range(0,len(numbers)):
        if numbers[counter] == search_value:
            print("Found at position ",counter + 1)
            found = True


found = False