Oct-12-2020, 07:36 AM
Hi everyone,
I wrote this code for a linear search. I would like the loop to keep running until all the positions of the number entered are found, but the loop gets interrupted once the first position is found. Example: If there are five 1s in the list at position 2, 28, 45, 105 and 189 then I will only get position 2 as the output and not the rest. I've tried replacing the 2nd while loop with a for loop, and replacing the True statement with a different value, but nothing seems to work. I'm out of ideas now. I'm not sure if it's a simple change in the 2nd while loop or if the code has to completely change there. Please help. Here is the code. Thanks in advance.
I wrote this code for a linear search. I would like the loop to keep running until all the positions of the number entered are found, but the loop gets interrupted once the first position is found. Example: If there are five 1s in the list at position 2, 28, 45, 105 and 189 then I will only get position 2 as the output and not the rest. I've tried replacing the 2nd while loop with a for loop, and replacing the True statement with a different value, but nothing seems to work. I'm out of ideas now. I'm not sure if it's a simple change in the 2nd while loop or if the code has to completely change there. Please help. Here is the code. Thanks in advance.
from random import randrange number_range = 500 values = [] found = False search = 0 found_indexes = [] run = 1 while run <= number_range: values.append(randrange(1, 201)) run = run + 1 print("The values are: ") for value in values: print(value, end = " ") print() criteria = int(input("What number should be searched for? ")) while search < number_range and found == False: if values[search] == criteria: found = True else: search = search + 1 if found == True: print("The number", criteria, "is located at position", search + 1) else: print("The number", criteria, "was not found.")