Open In App

Python Program for Linear Search

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[] using Python

Examples :

Input : arr[] = {10, 20, 80, 30, 60, 50, 
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].

A simple approach is to do a linear search, i.e

  • Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
  • If x matches with an element, return the index.
  • If x doesn’t match with any of the elements, return -1.

Example: linear-search1 Python Program for Linear Search Iterative Approach:

Python




# Searching an element in a list/array in python
# can be simply done using \'in\' operator
# Example:
# if x in arr:
#   print arr.index(x)
 
# If you want to implement Linear Search in python
 
# Linearly search x in arr[]
# If x is present then return its location
# else return -1
 
def search(arr, x):
 
    for i in range(len(arr)):
 
        if arr[i] == x:
            return i
 
    return -1


Python Program for Linear Search Recursive Approach: 

Python




# This is similar to the above one, with the only difference
# being that it is using the recursive approach instead of iterative.
 
 
def search(arr, curr_index, key):
    if curr_index == -1:
        return -1
    if arr[curr_index] == key:
        return curr_index
    return search(arr, curr_index-1, key)


The time complexity of the above algorithm is O(n). 

Auxiliary Space: O(1) for iterative and O(n) for recursive.

Please refer complete article on Linear Search and Difference Between Recursive and Iterative Algorithms for more details!

Python Program for Linear Search Using re method

This program uses the regular expression module re to search for a given element in a list. The list is first converted to a comma-separated string and the element is searched in the string using regular expression. If the element is found, the index of the element in the list is calculated by counting the number of commas before the match. If the element is not found, a message is displayed.

Algorithm

1.Import the re module
2.Initialize the input list and element to search for
3.Convert the list to a comma-separated string
4.Use regular expression to search for the element in the string
5.If the element is found, calculate the index of the element in the list by counting the number of commas before the match
6.If the element is not found, display a message
7.Output the result

Python3




import re
 
# Sample input
arr = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
x = 110
 
# Convert the array to a string
arr_str = ','.join(str(i) for i in arr)
 
# Use regular expression to search for the element in the string
match = re.search(r'\b{}\b'.format(x), arr_str)
 
# Output
if match:
    # Calculate the index by counting the number of commas before the match
    result = arr_str[:match.start()].count(',')
    print(f"Element {x} is present at index {result}")
else:
    print(f"Element {x} is not present in the array")


Output

Element 110 is present at index 6

Time Complexity:

The time complexity of this program is O(n) because we need to traverse the entire list to convert it to a string and count the number of commas before the match. The search using regular expression can also take some time depending on the length of the string, but it is generally considered to be a fast operation.

Space Complexity:

The space complexity of this program is O(n) because we need to store the entire list as a string in memory. Additionally, the regular expression module uses some memory for its operations. However, since the input size is relatively small in this case, the space complexity is not a major concern.



Previous Article
Next Article

Similar Reads

Python Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Univariate Linear Regression in Python
In this article, we will explain univariate linear regression. It is one of the simplest types of regression. In this regression, we predict our target value on only one independent variable. Univariate Linear Regression in Python Univariate Linear Regression is a type of regression in which the target variable depends on only one independent varia
6 min read
Python | Linear Programming in Pulp
Linear Programming (LP), also known as linear optimization is a mathematical programming technique to obtain the best result or outcome, like maximum profit or least cost, in a mathematical model whose requirements are represented by linear relationships. Linear programming is a special case of mathematical programming, also known as mathematical o
4 min read
Solve Two Linear Equations Using Python Sympy
We are given two linear equations and our task is to solve them by using Python Sympy library. In this article, we will cover different approaches to solve two linear equations using Sympy. Solve Two Linear Equations Using SympyBelow are some of the approaches by which we can solve two linear equations using Sympy in Python: Solving Equations with
2 min read
Python Program for Binary Search (Recursive and Iterative)
In a nutshell, this search algorithm takes advantage of a collection of elements that is already sorted by ignoring half of the elements after just one comparison. Compare x with the middle element.If x matches with the middle element, we return the mid index.Else if x is greater than the mid element, then x can only lie in the right (greater) half
4 min read
Python program to search for the minimum element occurring consecutively n times in a matrix
Given a matrix containing n rows. Each row has an equal number of m elements. The task is to find elements that come consecutively n times horizontally, vertically, diagonally in the matrix. If there are multiple such elements then print the smallest element. If there is no such element then print -1.Examples: Input : n = 4 mat[5][5] 2 1 3 4 5 3 2
4 min read
Python program to Search an Element in a Circular Linked List
A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input: CList = 6->5->4->3->2, find = 3 Output: Element is present Input: CList
3 min read
Python Program for Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal. Example: Input: n = 4, e = 6 0 -> 1, 0
3 min read
Python Program for Breadth First Search or BFS for a Graph
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, that unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all ve
3 min read
Linear Regression Using Tensorflow
We will briefly summarize Linear Regression before implementing it using TensorFlow. Since we will not get into the details of either Linear Regression or Tensorflow, please read the following articles for more details: Linear Regression (Python Implementation)Introduction to TensorFlowIntroduction to Tensor with TensorflowBrief Summary of Linear R
6 min read