deflinearsearch(arr, x):for i inrange(len(arr)):if arr[i]== x:return i
return-1
arr =[1,2,3,4,5,6,7,8]
x =4print("element found at index "+str(linearsearch(arr,x)))
deflinear_search(a, key):
position =0
flag =Falsewhile position <len(a)andnot flag:if a[position]== key:
flag =Trueelse:
position = position +1return flag
#this is really basic, but it'll do
Array =[1,2,3,4,5,6,7,8]#example arraydefLinearSearch(Array, SearchVal):#SearchVal= value you are looking forfor i inrange(len(Array)):if Array[i]== SearchVal:returnTruereturnFalse#once it has looped through all of the array and hasn't found#the search value, it will return False.
"""
Ordered Linear Search
- This version searches for 1 item, and returns all the occurrences of it
"""deford_lin(lst, item):
found =[]# Search list up to larger number, and get all indices where its foundfor i, num inenumerate(lst):if num > item:breakelif num == item:
found.append(i)return found
# 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 =2for position, item inenumerate(arr):if item == search_n:print("%d The searching number is at position %d inside the array."%(search_n,position+1))breakelse: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.
"""
deflocate_card(cards, query):# Create a variable position with the value 0
position =0# Set up a loop for repetitionwhileTrue:# Check if element at the current position matche the queryif cards[position]== query:# Answer found! Return and exit..return position
# Increment the position
position +=1# Check if we have reached the end of the arrayif position ==len(cards):# Number not found, return -1return-1