# 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!
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!