GOVERNMENT POLYTECHNIC COLLEGE
PERUNDURAI
DEPARTMENT
OF
COMPUTER ENGINEERING
1052234230 - DATA STRUCTURES USING PYTHON
LAB MANUAL
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 1 Write a program to implement any one python
data structure with the following operations
A) Create B) Add elements
C) Access elements D) Remove elements
Aim:
To write a program to implement python data structure with basic
operations.
Procedure:
1. Initialize list with elements.
2. Add elements to the list.
3. Access an element in the list by index.
4. Remove an element from the list.
Program:
# 1.create list
my_list = [116,117,118,119,120]
print("Initial List:",my_list)
#2.Add Element
my_list.append(121)
print("After Adding 121:", my_list)
#Adding an Element at a specific index
my_list.insert (2, 200)
print ("After inserting 200 at index 2:",my_list)
#3.Acces Element
print ("Element at index 2:",my_list[2])
# 3.Acces Element
print("Last element:",my_list[-1])
# 4.Remove Element
my_list.remove(200)
print("After remove 10:",my_list)
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No.2.
Write a python program to implement a singly linked list.
a) create a singly linked list
b) add element to singly linked list
c) Remove element from singly linked list
Aim:
To Write a python program to implement a singly linked list.
Procedure:
1. Create a singly linked list: Initialize an empty linked list.
2. Add element to singly linked list: Add an element to the end
of the linked list.
3. Remove element from singly linked list: Remove an element
from the linked list.
Progam:
class Node:
def __init__(self, data):
self.data = data
self.Next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def create_list(self, data):
new_node = Node(data)
self.head = new_node
print(f"List created with the element: {data}")
def add_element(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
last_node = self.head
while last_node.Next:
last_node = last_node.Next
last_node.Next=new_node
print(f"Element {data} added to the list.")
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
def remove_element(self, data):
if self.head is None:
print("Error: The list is empty!")
return
if self.head.data == data:
self.head = self.head.Next
print(f"Element {data} removed from the list.")
return
current_node = self.head
while current_node.Next and current_node.Next.data != data:
current_node = current_node.Next
if current_node.Next is None:
print(f"Error: Element {data} not found in the list.")
else:
current_node.Next = current_node.Next.Next
print(f"Element {data} removed from the list.")
def display(self):
if self.head is None:
print("The list is empty.")
return
current_node = self.head
print("Elements in the list:")
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.Next
print("None")
if __name__ == "__main__":
linked_list=SinglyLinkedList()
linked_list.create_list(10)
linked_list.add_element(20)
linked_list.add_element(30)
linked_list.add_element(40)
linked_list.display()
linked_list.remove_element(20)
linked_list.display()
linked_list.remove_element(100)
linked_list.remove_element(10)
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
linked_list.display()
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 3. Write a python program to implement stack
Aim:
Simple Python program that implements a stack with basic operations
Procedure:
1. Push: Add an element to the stack.
2. Pop: Remove the top element from the stack.
3. Peek: View the top element of the stack.
4. IsEmpty: Check if the stack is empty.
Program:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"{item} pushed to stack")
def pop(self):
if not self.is_empty():
popped_item = self.stack.pop()
print(f"{popped_item} popped from stack")
else:
print("Stack is empty, cannot pop")
def is_empty(self):
return len(self.stack) == 0
if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.pop()
stack.pop()
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 4 Write a python program to implement queue
Aim:
Simple Python program to implement queue with basic operations.
Procedure:
1. Enqueue: Add an element to the end of the queue.
2. Dequeue: Remove the front element from the queue.
3. IsEmpty: Check if the queue is empty.
Program:
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
print(f"{item} enqueued to queue")
def dequeue(self):
if not self.is_empty():
dequeued_item = self.queue.pop(0)
print(f"{dequeued_item} dequeued from queue")
else:
print("Queue is empty, cannot dequeue")
def is_empty(self):
"""Check if the queue is empty."""
return len(self.queue) == 0
if __name__ == "__main__":
queue=Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.dequeue()
queue.dequeue()
queue.dequeue()
queue.dequeue()
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 5 : Write the python program for pre-order traversal of a
binary tree
Aim:
To write the python program for pre-order traversal of a binary tree.
Procedure:
1. Start.
2. If the root is empty, return.
3. Traverse the root node. //print value at node
4. Traverse left subtree of theroot.
//preorder(root.leftChild)
5. Traverse the right subtree of the root.//
preorder(root.rightChild)
6. End.
Program:
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild=None
def insert(root,newValue):
if root is None:
root=BinaryTreeNode(newValue)
return root
if newValue<root.data:
root.leftChild=insert(root.leftChild,newValue)
else:
root.rightChild=insert(root.rightChild,newValue)
return root
def preorder(root):
if root==None:
return
print(root.data)
preorder(root.leftChild)
preorder(root.rightChild)
root=insert(None,15)
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
insert(root,10)
insert(root,25)
insert(root,6)
insert(root,14)
insert(root,20)
insert(root,60)
print("Printing values of binary tree in preorder Traversal.")
preorder(root)
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 6. Write a python program to implement bubble sort
Aim:
To write a python program to implement bubble sort
Procedure:
1. Compare the first and second elements of the list.
2. If the first element is greater than the second, swap them.
3. Continue comparing and swapping adjacent elements throughout the
list.
4. After each pass, the largest element "bubbles up" to its correct
position.
5. Repeat this process for all elements until no swaps are needed (i.e.,
the list is sorted).
Program:
def bubble_sort(a):
n=len(a)
for i in range(n):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
n=int(input("enter the number of element in the list:"))
a=[]
for i in range(n):
element=int(input(f"enter element{i+1}:"))
a.append(element)
print("original list:",a)
bubble_sort(a)
print("sorted list:",a)
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 7:
Write a python program to implement linear search
Aim:
To write a python program to implement linear search
Procedure:
1. Start from the first element and compare it with the target element.
2. If the element matches the target, return its index.
3. If the element does not match, move to the next element.
4. If the element is not found by the time the end of the list is reached,
return -1 to indicate that the element is not present in the list
Program:
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
n = int(input("Enter the number of elements in the list: "))
l1 = []
for i in range(n):
element = int(input(f"Enter element {i+1}: "))
l1.append(element)
value = int(input("Enter the value to search for: "))
pos = linear_search(l1, value)
if pos != -1:
print(f"Value found at position {pos+1}.")
else:
print("Value not found.")
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
Ex. No. 8 :
Write a python program to implement binary search
Aim:
To write a python program to implement binary search
Procedure:
1. Begin with the middle element of the list.
2. If the target element is equal to the middle element, the search is
complete.
3. If the target is less than the middle element, repeat the search on
the left half of the list.
4. If the target is greater than the middle element, repeat the search
on the right half of the list.
5. If the search interval becomes empty, the target is not present in
the list
Program:
def binary_search(a, x):
left = 0
right = len(a) - 1
while left <= right:
mid = (left + right) // 2
midvalue = a[mid]
if midvalue == x:
return mid
elif midvalue < x:
left = mid + 1
else:
right = mid - 1
return -1
n = int(input("Enter the number of elements in the sorted list: "))
sortlist = []
for i in range(n):
element = int(input(f"Enter element {i+1}: "))
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053
sortlist.append(element)
x = int(input("Enter the target value to search for: "))
pos = binary_search(sortlist, x)
if pos != -1:
print(f"Value found at index {pos}.")
else:
print("Value not found.")
Output:
GOVERNMENT POLYTECHNIC COLLEGE PERUNDURAI-638053