Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

linear search algorithm in python

# Linear Search:

"""
Another classic example of a brute force algorithm is Linear Search. 
This involves checking each item in a collection to see if it is the 
one we are looking for.
In Python, it can be implemented like this:

"""

arr = [42,2,3,1,4,6]
search_n = 2
for position, item in enumerate(arr):
    if item == search_n:
        print("%d The searching number is at position %d inside the array."%(search_n,position+1))
        break
else:
    print("Sorry! Not Found.")
    
"""
Of course there are many different implementations of this algorithm. 
I like this one because it makes use of Python’s very handy enumerate function. 
Regardless of the details of the implementation, 
the basic idea remains the same – iterate through the collection (in the case above, a Python list), 
and check if each item is the target.I like to use the variable names search_n and array from the 
expression looking for a search_n in a array.
"""
 
PREVIOUS NEXT
Tagged: #linear #search #algorithm #python
ADD COMMENT
Topic
Name
1+8 =