0

Is this valid as an implementation of a linear search algorithm?

https://code.sololearn.com/cn7n7C6O0Vv2/?ref=app

14th May 2021, 3:22 PM
K.S.S. Karunarathne
K.S.S. Karunarathne - avatar
2 Respostas
+ 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
14th May 2021, 6:52 PM
visph
visph - avatar
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.
14th May 2021, 4:21 PM
Tibor Santa
Tibor Santa - avatar