0
Is this valid as an implementation of a linear search algorithm?
2 Respuestas
+ 1
# here's a valid implementation of a linear search algorithm, using only one loop, as suggested by Tibor Santa:
def linear_search(x,lst):
for i in range(len(lst)):
if x == lst[i]:
print(i)
return
print(-1)
x = [2,34,44,81,3]
linear_search(3,x)
linear_search(4,x)
linear_search(44,x)
# builtin names are not recommended to be overrided in global namespace, however it could be acceptable to use them inside function namespace, if you doesn't need to use it in that function ^^ however, it's even considered as bad practice, because this could be a problem if you later need to use it inside the function ;P
0
I think if you design an algorithm like this, you are not really supposed to use builtin methods like index()
In your code you are technically looping through the list twice, because "index(x)" and also "x in list" does that.
Try to use a normal for loop instead, and break or return when the value is found.
Also, it is bad to use "list" as a function parameter, because you are overriding a builtin function.