# linear_search.py
# This program uses a linear search of an array of size n for
# value x
# by: Scott Gordon
things = ["bike", "house", "cat", "computer", "hammer"]
def linear_search(array, n, x):
answer = "Not found!"
for i in range(1, n):
if array[i] == x:
answer = i
return answer
print(linear_search(things, 5, "cat")) # prints the index of "cat" which is 2
print(linear_search(things, 5, "hammer")) # prints the index of "hammer" which is 4
print(linear_search(things, 5, "pasta")) # prints Not found!
![Cover image for Linear Search](https://media.dev.to/cdn-cgi/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fclof9sp276325p4mx9ox.jpg)
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (2)
Why not this? It break the loop when find the element, there is another way by getting the length of the array too. :D
yeah, i had added that to the better linear search algo after this one. And yes using len(array) is more Pythonic but I was trying to write it as close to psuedocode as possible while still using Python.
Thanks for the suggestions though!