pythonlistlinear-search

doing a linear search python code for a list and for some reason im getting both conditions satisfied, can someone help me with this


K=[30,15,25,50,40,35,44,49,55,54]

Search = int(input("enter the value you want to search"))
Index=0
Found=False

while Index<=9 and Found==False:
    if K[Index]==Search:
        print("Match found")
        Found=True

    else:
        print("Match not found")
        Index=Index+1

the result for this code when the value used are 15 comes out as;

Match not found

Match found

however, when i enter the value to be searched as 30 the results come out correctly as;

Match found

however when i enter 54 as the value to be searched the results come out as;

Match not found

Match not found

Match not found

Match not found

Match not found

Match not found

Match not found

Match not found

Match not found

Match found

can someone help me figure out why the results differ in this way for each value tested, what's wrong with my code and also what do I do to fix it also, I'm a beginner and have no idea what I'm doing yet so I might have made a dumb mistake and also I'm aware there are easier ways of searching up values in a list but I need to learn this specific method so please help me with this one


Solution

  • 15 is the second item in your list K, and your while loops through every list element.

    If you think about how the program runs, you'll see that the loop goes through every item in then list before Search is found.

    So, when you enter 15, your program goes through the all elements of the list before 15. The only item before 15 is 30, so before returning Match found for 15, it returns Match not found.

    Similarly, 54 is the 10th item in your list, so your program prints Match not found 9 times, and Match found on the tenth.

    One solution to this would be to simply not print Match not found until the last element of the list has been reached.

    That would look like this:

    K = [30,15,25,50,40,35,44,49,55,54]
    
    Search = int(input("Enter the value you want to search: "))
    Index = 0
    Found = False
    
    while Index<=9 and not Found:
        if K[Index]==Search:
            print("Match found")
            Found=True
        else:
            if Index==9:
                print("Match not found")
            Index=Index+1
    

    There are better ways to do this while still doing a linear search, but this method is easy to understand.

    It is possible that you don't NEED to do a linear search, in which case you can use in to check wether a list contains something. For example:

    print('Found!' if Search in K else 'Not found.')
    

    Hope this helps!