Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linear search issue
#1
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. 
 
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.")
Reply
#2
You are making it difficult for yourself :-)
I would replace your while loop, because there will be only one "True", 
and your counting is only for mismatches.

Just look 'for criteria in values:', and each time it matches, you have a hit;
Paul
Reply
#3
Generally in Python one uses for-loop for defined number of repeats and while-loop until condition is met. So:
# instead of this javasque way

run = 1
while run <= number_range:
    values.append(randrange(1, 201))
    run = run + 1

# you can do it in Python way:

for i in range(number_range):                 # or range(500)
    values.append(randrange(1, 201))

# but you could also do this:

from random import choices

values = choices(range(1, 201), k=500)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
(Oct-12-2020, 08:41 AM)DPaul Wrote: You are making it difficult for yourself :-)
I would replace your while loop, because there will be only one "True", 
and your counting is only for mismatches.

Just look 'for criteria in values:', and each time it matches, you have a hit;
Paul

Hi. So, I almost got it. Now it's giving me all the positions. Is this what you meant? Or is still too complicated ;).
 
 
from random import randrange

number_range = 500
values = []

found = False
search = 0

found_indexes = []  #I added another variable for the FOR loop

for i in range(number_range):       #thanks [b]perfringo[/b] :)          
    values.append(randrange(1, 201))

print("The values are: ")
for value in values:
    print(value, end = " ")
print()

criteria = int(input("What number should be searched for?  "))

for index, value in enumerate(values):
    if value == criteria:
        found_indexes.append(index)

print("The number", criteria, "is located at positions", found_indexes)
Only prob I have now is how to implement the if statement ( see below ) at the end to get a negative output incase the number is not in the list. I'm sure Ill get it as well. My head is going to explode though. 
 
 
if .................?
    print("The number", criteria, "is located at positions", found_indexes)
else:
    print("The number", criteria, "was not found.")
Thanks for the help guys!
Reply
#5
Hi, I managed to get it. Question: How do I get rid of the brackets in the output? 
from random import randrange

number_range = 500
values = []

search = 0
found_indexes = []

#generate random values
for i in range(number_range):                
    values.append(randrange(1, 201))
#asking user input
print("The values are: ")
for value in values:
    print(value, end = " ")
print()

criteria = int(input("What number should be searched for?  "))

#searching
for search, value in enumerate(values):
    if value == criteria:
        found_indexes.append(search)
    
#printing
if len(found_indexes):
  print("The number", criteria, "is located at positions", found_indexes)
else:
    print("The number", criteria, "was not found.")
Reply
#6
One way is to take advantage of f-strings:
 
 
>>> criteria = 5
>>> found_indexes = [1, 42, 77]
>>> print(f"The number {criteria} is located at positions {', '.join(str(i) for i in found_indexes)}")
The number 5 is located at positions 1, 42, 77
Instead of checking len() you can directly apply Truth Value Testing:
Quote:/../ built-in objects considered false:
     /../ empty sequences and collections: '', (), [], set(), range(0)

So you can write:
if found_indexes:
EDIT: if it is not about 'linear search' then one can during populating the list of values also check for equality with desired value and append it to indices list if True. for-loop generated i is equal to index of value in list.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Linear Search just_started_python 2 3,809 Nov-17-2016, 12:05 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020