Master the #Basics: Learn #Linear #Search Algorithm in just 1 minutes! with #Python Implementation.

preview_player
Показать описание
brief #introduction about #linear #search with an #implementation on #python:

Linear search is a simple search algorithm that involves sequentially checking each element of a list or an array until a target element is found or all elements have been searched. The time #complexity of linear search is O(n) in the worst case scenario, where n is the number of elements in the list or array.

Here's an implementation of linear search in Python:

python code
```
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
```
This implementation takes a list "arr" and a target element "target" as inputs and returns the index of the target element if it is found in the list, or -1 if the target element is not in the list.
Рекомендации по теме
Комментарии
Автор

Nice short !

I know that you tried to keep things simple and legible (even for non Python users), but I still think that it would be preferable to keep a "pythonic" way of writing code in your examples. It is not really advised to manually index or manage an additional state variable, especially when there's a native, dedicated way to do it with one function call (compared to two: range, len)

I do think that:

def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1

is still very legible even for someone who does not use Python (especially if writing 'index' and 'element' an explicit way ^^). Plus, along with your explanations, you will teach good coding practice for that language (which is always a good option ^^)

jean-marcfraisse
Автор

Much easier:
for i in range (X):
If input(f"is {X[I]} the number you are looking for?") == "Sure":
Return X.index(X[I])

rondamon
Автор

So is this the algorithm behind the find method?

CraszyAsce