1

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) 
6
  • 2
    What do you mean by not working? Are there errors? Commented Aug 7, 2017 at 22:52
  • You could just do for j, el in enumerate(data): if el == s: return j Commented Aug 7, 2017 at 22:54
  • 4
    Are you sure this is python3? raw_input doesn't exist in Python 3 - it's a Python 2 equivalent of input() Commented Aug 7, 2017 at 22:54
  • 1
    @SumnerEvans, but if you need to return the index? usually use enumerate() there Commented Aug 7, 2017 at 22:55
  • Don't return -1 when s is not found; raise an exception! Commented Aug 7, 2017 at 22:57

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

-2

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) 

2 Comments

No, you don't want to switch raw_input to input if you are in Python 2.
This is only working by accident, and that accident is a potential security problem if you were to use similar code in a real application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.