Shubham Gupta
Shubham Gupta

Reputation: 13

Linear Search Code in python

This is linear search code but it is not working can anyone help me out!!

data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
    x = raw_input('Enter the numbers into the array: ')
    data.append(x)

print(data)

def lSearch(data, s):
    for j in range(len(data)):
        if data[j] == s:
            return j
    return -1

s = int(input('Enter the element do you want to search: '))
result = lSearch(data, s)

if result == -1:
    print("The Element is not found")
else:
    print("The element is an array at index %d",result) 

Upvotes: 0

Views: 976

Answers (2)

Shubham Gupta
Shubham Gupta

Reputation: 13

thanks to everyone.Now , my code is running by a simple change raw_input to input(). data = []

n = int(input('Enter how many elements you want: '))

for i in range(0, n):

x = input('Enter the numbers into the array: ')

data.append(x)

k = sorted(data)

print(k)

def lSearch(k, s):

for j in range(len(k)):

    if k[j] == s:

        return j

return -1

s = int(input('Enter the element do you want to search: '))

result = lSearch(k, s)

if result == -1:

print("The Element is not found")

else:

print("The element is an array at index %d",result) 

Upvotes: -2

TerryA
TerryA

Reputation: 60024

s is an integer, but your list will be full of strings since you append x to it.

x = raw_input('Enter the numbers into the array: ')

See here x is a string. You have not converted this to an int (unlike at other places)


If this is actually Python 3 and not Python 2 (as it says in your tags), then you should be using input() not raw_input() (raw_input doesn't actually exist in Python 3). input() will return a string in Python 3 (unlike in python2, where it might return an integer).

Upvotes: 4

Related Questions