线性搜索不会继续结束数组

问题描述 投票:1回答:3

该程序旨在显示所有数字为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

python-3.x
3个回答
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)

0
投票

你的程序在找到71的第一次出现后停止,因为在那一点上found的值将变为True,这将导致and运算符的一侧为Falsefound == False)因此整个条件将是False因为'和'运营商要求双方都是True,以便评估True

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

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")

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
© www.soinside.com 2019 - 2024. All rights reserved.