Linear Search - Matching integer with list

718 views Asked by At

Hi am new to python here is what am trying to do , i have this below list.

x= [1,2,3,4,5,6,7,8,9]

and here is my python code:

length = len(x)
c = input("Enter a no\n")

for i in range (length):
    if  x[i] == c:
        print ("Found at position ", i)
    else:
        print("not found")

and the output am receiving.

Enter a no
2
not found
not found
not found
not found
not found
not found
not found
not found
not found

Now with my very few little knowledge what i figured out is this multiple not found is happening because every time loop takes a no checks with the list and if its not available its moving to else part due to lack no proper beak statement but what am not able to figure out that when it takes to in x[i] its matching then output should be Found at position 1 . i read somewhere need to use if c in x[i] but it didn't work. on the hand i re-wrote the code.

def ls():
    t = int(input("Enter your search no \n"))
    for i in x:
        if i!= t:
            continue
        print("Your value is present in ")

        break
    else:
        print ("parrrrrrrrrrr")

ls()

which is working all good. It will be of help if i can get to know:

  • with 1st program why its showing not found even the input is present in the list
  • the part where c in x[i] was entered same issue happened as per my knowing (which now makes no-sense) it should also work
  • if it is the case of integer vs list then how my 2nd code is working -is it the rigt way to do linear search.
1

There are 1 answers

4
Oleh Rybalchenko On BEST ANSWER
  1. Because input returns you a str object and then compared with int object without implicit conversion, so the expression always be False.
  2. c in x where x is a list works, but x[i] is an integer in your case
  3. 2nd code is working because you convert the input into int implicitly

The most elegant way in my opinion is:

c = input("Enter a no\n")
items = [1,2,3]
print(items.index(int(c)) if int(c) in items else 'Not found')

And of course dont forget to catch ValueError if input is not convertable into integer