467,166 Members | 1,044 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,166 developers. It's quick & easy.

linear search

The search is always canceled after the first hit. How can I correct this? I dont want to cancel.


Expand|Select|Wrap|Line Numbers
  1. from random import randrange
  2.  
  3. # the max number of values
  4. NumberValue = 100
  5.  
  6. # an empty list for the values
  7. ListOfNumberValue = []
  8.  
  9.  
  10. found = False
  11.  
  12. search = 0
  13.  
  14. print("linear search")
  15.  
  16. runThrough = 1
  17. while runThrough <= NumberValue:
  18.     ListOfNumberValue.append(randrange(1, 201))
  19.     runThrough = runThrough + 1
  20.  
  21.  
  22. print("the values are: ")
  23. for value in ListOfNumberValue:
  24.     print(value, end = " ")
  25. print()
  26.  
  27. lookingFor = int(input("What to look for? "))
  28.  
  29.  
  30. while search < NumberValue and found == False:
  31.     if ListOfNumberValue[search] == lookingFor:
  32.         found = True
  33.     else:
  34.         search = search + 1
  35.  
  36. if found == True:
  37.     print("Value", lookingFor, "is at position", search + 1)
  38. else:
  39.     print("Value", lookingFor, "was not found.")
Nov 29 '20 #1
  • viewed: 2301
Share:
1 Reply
Banfa
Expert Mod 8TB
This code is only meant to find the first occurance because
  1. It sets a flag as soon as it finds what your search for and uses that flag to halt the loop
  2. It uses a single variable, search, to store the found index which is also the loop counter so it can't store more than 1 result

To make if find multiple results then you need to
  1. Stop the loop using found as a stop condition
  2. Add a veritable, list or array, to store the results so there can be more than 1
  3. Change the output to use the results in the new variable
Nov 29 '20 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

28 posts views Thread by joshc | last post: by
2 posts views Thread by littlegirl | last post: by
3 posts views Thread by nembo kid | last post: by
1 post views Thread by Mahjabeen | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.