linear search

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thomasBaldr99
    New Member
    • Nov 2020
    • 1

    linear search

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


    Code:
    from random import randrange
    
    # the max number of values
    NumberValue = 100
    
    # an empty list for the values
    ListOfNumberValue = []
    
    
    found = False
    
    search = 0
    
    print("linear search")
    
    runThrough = 1
    while runThrough <= NumberValue:
        ListOfNumberValue.append(randrange(1, 201))
        runThrough = runThrough + 1
    
    
    print("the values are: ")
    for value in ListOfNumberValue:
        print(value, end = " ")
    print()
    
    lookingFor = int(input("What to look for? "))
    
    
    while search < NumberValue and found == False:
        if ListOfNumberValue[search] == lookingFor:
            found = True
        else:
            search = search + 1
    
    if found == True:
        print("Value", lookingFor, "is at position", search + 1)
    else:
        print("Value", lookingFor, "was not found.")
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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

    Comment

    Working...