Python Code for Linear Search in a List
Python Code for Linear Search in a List
In this Python code example, we’ll learn how to implement a linear search algorithm to
check if a number is present in a list. Linear search is a basic search algorithm that
sequentially checks each element in a list until a match is found or all the elements have
been exhausted. We’ll define a function called `linearSearch()` that takes a number
and a list as input and returns the position of the number if it is present in the list, or None
if it is not.
Linear Search
Linear Search is a searching algorithm in which we sequentially search for a presence of a
particular element inside a list or array.
Logic:
Define a function called `linearSearch()` that takes two parameters: `num` and
`list1`.
Iterate through the elements in the list using a `for` loop and the `range()`
function.
Check if the current element in the list is equal to the provided number (`num`).
If a match is found, return the index (`i`) of the element in the list.
If no match is found after iterating through all the elements, return None.
Create an empty list called `list1`.
Prompt the user for the maximum number of numbers they want to enter in the list.
Use a `for` loop and the `input()` function to add the numbers to the list using
the `append()` method.
Prompt the user to enter the number they want to search for in the list.
Call the `linearSearch()` function with the provided number and the list.
Check if the result returned by the function is None.
If it is, print a message stating that the number is not present in the list.
If it is not None, print a message stating that the number is present at the position
returned by the function.
Source Code
def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num:
return i
return None
list1 = []
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n)
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")
Output
How many numbers do you want to enter in the list:5
Enter a list of numbers:
1
2
3
4
5
Enter the number to be searched: 4
Number 4 is present at 4 position
Binary Search Algorithm in Python
Binary search is a highly efficient search algorithm used to find a specific element within a
sorted list. This tutorial provides a comprehensive guide to implementing the binary search
algorithm in Python. You’ll learn the step-by-step process of binary search, its underlying
logic, and how it quickly locates elements in a sorted list.
Binary Search is a searching algorithm to find the position of the specific element present
inside a sorted array or list.
Binary Search is also called a half-interval search.
It is the fastest searching algorithm with time complexity of O(logn).
Binary Search is based on a divide & conquer strategy.
Example:
Logic:
Define the binarySearch function that takes a list list and a search key as input.
Initialize the search range pointers first and last to the beginning and end of the list,
respectively.
Perform binary search while the search range is valid (first is less than or equal to last).
Calculate the index of the middle element using integer division.
Compare the middle element with the search key.
If they are equal, return the index mid indicating the key’s position.
If the key is greater, adjust the search range to the right half of the list.
If the key is smaller, adjust the search range to the left half of the list.
If the key is not found within the loop, return -1 to indicate its absence in the list.
Source Code
def binarySearch(list, key):
first = 0
last = len(list) - 1
while first <= last:
mid = (first + last) // 2
if list[mid] == key:
return mid
elif key > list[mid]:
first = mid + 1
elif key < list[mid]:
last = mid - 1
return -1
list1 = [] # Create an empty list
print("Create a list by entering elements in ascending order")
print("Press enter after each element, press -999 to stop")
num = int(input())
while num != -999:
list1.append(num)
num = int(input())
Output
Create a list by entering elements in ascending order
Press enter after each element, press –999 to stop
1
3
5
7
9
11
13
15
-999
Enter the key to be searched: 7
7 is found at position 4
Python Turtle Graphics
Turtle is a special feature of Python. Using Turtle, we can easily draw in a drawing board.
First, we import the turtle module. Then create a window, we create a turtle object, and
using the turtle() method we can draw on the drawing board.
Turtle Graphics Design – 1
Source Code
import turtle
def draw_attractive_design1():
colors = ["red", "orange", "yellow", "green", "blue",
"purple"]
pen = turtle.Turtle()
pen.speed(10)
turtle.bgcolor("black")
pen.pensize(2)
for i in range(180):
pen.color(colors[i % 6])
pen.forward(200)
pen.right(61)
pen.forward(100)
pen.right(120)
pen.forward(100)
pen.right(61)
pen.forward(200)
pen.right(181)
pen.hideturtle()
draw_attractive_design1()
turtle.done()
Source Code
import turtle
def draw_attractive_design2():
colors = ["red", "orange", "yellow", "green", "blue",
"purple"]
pen = turtle.Turtle()
pen.speed(10)
turtle.bgcolor("black")
pen.pensize(2)
initial_size = 30
for i in range(200):
pen.color(colors[i % 6])
pen.forward(initial_size + i)
pen.left(59)
pen.hideturtle()
draw_attractive_design2()
turtle.done()
Source Code
import turtle
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("yellow") # Background color
# Create turtle
t = turtle.Turtle()
t.color("black")
t.shape("turtle")
t.speed(3)