Skip to main content

Linear Search Using Functions Python

                                               

Problem:

                    We need to search an element from an list. We have variety of methods to search an element from an array but the simple way of search is "Linear Search" method. We just need a loop traversing the array and search for match. We can see  two ways for achieving linear search in this post. 

Method 1:

                Here we just directly give the values of array and value to search in default , the code follows.

list1=[2,3,1,4,5]
key=2

for i in range(len(list1)):
    if list1[i]==key:
        print("Number found")

            The loop takes range as 0,1,2,3,4 and traverse list elements. We have a conditional statement to check the key is in the list. If the key is found it returns output or else it does not display output.

Method 2:

            In this method I has used functions and got inputs from the user, and the code follows. 

#function for linear search
def linearsearch(a,k):
    for i in range(len(a)):
        if a[i] == k:
            print("Number found")

# input from the user
list1=list(map(int,input("Enter array elements:").split(',')))
key= int(input("Enter the value to search:"))

linearsearch(list1,key)

            Here I used a function and paassed the list and the key to it and inside that function we have the Method 1 code in it which the concept of the code. I has used "map function"  to get inputfrom the user and converted it to a list they I got the value of key and called the function.

Comments

Popular posts from this blog

Palindrome Checker Using Python

  Problem:               To find whether a given input is a palindrome or not. We use two methods to find the palindrome, one is using "reverse indexing" and "reverse function". Palindrome:  The term palindrome means, consider a string and reverse it then compare both the                                 string if they are equal then it is a palindrome. Code: def palindrome ( a ):     if a == a [::- 1 ]:         print ( "It is a Palindrome" )     else :         print ( "It is not a Palindrome" ) val = input ( "Enter the value" ) palindrome ( val )