WEEK - 1
1. Python program to Use and demonstrate basic data structures.
▪ Set operations
1.Write a python code to print UNION of 2 sets
Code:
D1 = {"mon", "tue", "web"}
D2 = {"thu", "web", "fri"}
D3 = (D1 | D2)
print(D3)
Output:
{'tue', 'thu', 'web', 'mon', 'fri'}
2. Write a python code to print INTERSACTION of 2 sets
D1 = {"mon", "tue", "web"}
D2 = {"thu", "web", "fri"}
D3 = (D1 & D2)
print(D3)
Output:
{'web'}
3. Write a python code to print DIFFERENCE of 2 sets
D1 = {"mon", "tue", "web"}
D2 = {"thu", "web", "fri"}
D3 = (D1 - D2)
res =D1.difference(D2)
print(res)
Output:
{'tue', 'mon'}
▪ Set comprehension
Code, execute and debug programs to perform following
mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = set()
for element in mySet:
newSet.add(element**2)
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)
Output:
The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
Python code to deleting tuple
tuple1=(1,2,3,4,5,6)
print("contents of tuple=",tuple1)
# Error is thrown as tuples are inmutable
del tuple1[0]
print(tuple1)
del tuple1
print("tuple after deleting all elements",tuple1)
Output :
contents of tuple= (1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "C:\Users\is new lab07\Desktop\21CS018 III SEM\pythonProject\DELETING
TUPLE.py", line 5, in <module>
Membership operator for tuple
Tuple=(10,26,44)
print(10 in Tuple)
print(50 in Tuple)
print(65 not in Tuple)
Output:
True
False
True
Converting list to s tuple
list1=[0,1,2]
print(tuple(list1))
print(tuple('python'))#string'python'
Output:
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Process finished with exit code 0
Iterating through a tuple
ice_cream_flavors=('Chocolate','Vennilla','Mint',
'Strawberry','Chock-chip')
for f in ice_cream_flavors:
print(f)
Output :
Chockolate
Vennilla
Mint
Strawberry
Chock-chip
Basic operations on List
list=['physics','chemistry',1997,2000]
print("List 0th element :",list[0])
Output:
List 0th element : physics
Updating lists
list=['physics','chemistry','computer',2000];
print("value available at index 2:")
print(list[2])
list[2]=2001;
print("new value available at index 2 :")
print(list[2])
Output:
value available at index 2:
computer
new value available at index 2 :
2001
Delete list elements
list1=['physics','chemistry',1997,2000]
print("Before deleting value at index 1 :")
print(list1)
del(list1[1]);
print("After deleting value at index1:")
print(list1)
Output:
Before deleting value at index 1 :
['physics', 'chemistry', 1997, 2000]
After deleting value at index1:
['physics', 1997, 2000]
Traversing list
list=[0,1,2,3,4,5]
i=0
while i<len(list):
print(list[i])
i=i+1
Output:
0
1
2
3
4
5
Concatenation operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
l3=list1+list2
print("result of concatenation :",l3)
Output:
result of concatenation : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Repetition operator
list_one=[10,20,30]
list_two=list_one*2
print("repitation of list=",list_two )
list_one=[10,20,30]
list_two=[list_one*2.0] #Error
print(list_two)
Equality operator
list_one=['Mon','Tue','Web']
list_two=['Mon','Tue','Web']
list_three=['mon','tue','web']
list_four=['web','tue','mon']
print(list_one==list_two)
print(list_one==list_three)
print(list_two==list_three)
print(list_three==list_four)
print(list_two!=list_three)
print(list_three!=list_four)
Output:
True
False
False
False
True
True
Relational operator list
list_one=[10,20,30,40]
list_two=[30,40,50]
print(list_one<list_two)
print(list_two>list_one)
print(list_one>=list_two)
print(list_two<=list_one
Output:
True
True
False
False
Indexing
mylist=[1,2,3,4,5,6,7,8,9]
print("First element in the list",mylist[0])
print("second element in the list",mylist[1])
print("Third element in the list",mylist[2])
print("last element in the list",mylist[-1])
Output:
First element in the list 1
second element in the list 2
Third element in the list 3
last element in the list 9
Slicing
mylist=[1,2,3,4,5,6,7,8,9]
print("First to third in the list",mylist[0:3])
print("second to fifth in the list",mylist[1:6])
print("fourth to seventh in the list",mylist[4:7])
Output :
First to third in the list [1, 2, 3]
second to fifth in the list [2, 3, 4, 5, 6]
fourth to seventh in the list [5, 6, 7]
Comprehension
even_nums = []
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Python program to demonstrate basic int, float, string, Boolean data structures.
#Integers, Float,Strings, Boolean
print("integer data type")
a-20
b-30
print(a,b)
print("addition\n",a+b)
print("substraction\n",a-b)
print("multiplication\n",a*b)
print("division\n",a/b)
print("reminder\n",a%b)
print("float data type")
a-2.3
b-4.67
print(a,b)
print("addition\n",a+b)
print("substraction\n",a-b)
print("multiplication\n",a*b)
print("division\n",a/b)
print("reminder\n",a%b)
print("string data type")
a='wel come'
b='fourth sem'
print("combining\n",a+b)
print("string data type\n")
a=30
b-45
print("comparision result is\n",a>b)
OUTPUT
integer data type
20 30
Addition
50
Substraction
-10
Multiplication
Data structures with Python Lab
600
Division
0.6666666666666666
Reminder
20
float data type
2.3 4.67
Addition
6.97
Substraction
-2.37
multiplication
10.741
Division
0.49250535331905776
reminder
2.3 string data type
combining
wel come fourth sem
string data type
2. Implement an ADT with all its operations
● First we have to make a file as Student_ADT.py and save it and put the functions
in this.
CODE
class Student:
def __init__(self,name,rollno,mark1,mark2,mark3):
self.name=name
self.rollno=rollno
self.marks=[]
self.marks.append(mark1)
self.marks.append(mark2)
self.marks.append(mark3)
def display(self):
print("Student Details are")
print("Name:",self.name)
print("Roll Number:",self.rollno)
print("Marks of student are",self.marks)
def getmarks(self):
return self.marks
● Next create another python file and save as student2.py and import ADT file
using Import statement and also put the code in it.
CODE
from Student_ADT import *
s1=Student("MANJU",1,20,25,30)
s2=Student("PAVAN",2,25,20,35)
s3=Student("Manu",3,30,35,40)
s1.display()
studentmarks=s1.getmarks()
average=sum(studentmarks)/len(studentmarks)
print("Average Marks of Student is",average)
s2.display()
studentmarks=s2.getmarks()
average=sum(studentmarks)/len(studentmarks)
print("Average Marks of Student is",average)
s3.display()
studentmarks=s3.getmarks()
average=sum(studentmarks)/len(studentmarks)
print("Average Marks of Student is",average)
OUTPUT
Average Marks of Student is 25.0
Student Details are
Name: MANJU
Roll Number: 2
Marks of student are [25, 20, 35]
Average Marks of Student is 26.666666666666668
Student Details are
Name: PAVAN
Roll Number: 3
Marks of student are [30, 35, 40]
Average Marks of Student is 35.0
WEEK-2
1. Implement an ADT and Compute space and time complexities.
# student ADT
class Student:
def _init_(self, name,rollno ,mark1,mark2,mark3):
self.name=name
self.rollno=rollno
self.marks=[]
self.marks.append(mark1)
self.marks.append(mark2)
self.marks.append(mark3)
def display(self):
print(" student details are")
print("Name",self.name)
print(" roll number:",self.rollno)
print(" marks of students are",self.marks)
def getmarks(self):
return self.marks
from Student_ADT_main import *
import time
from sys import getsizeof
start_time = time.time()
s1=Student("Anil",1,20,25,30)
s2=Student("Sunil",2,25,20,35)
s3=Student("Manu",3,30,35,40)
s1.display()
studentmarks=s1.getmarks()
average=sum(studentmarks )/len(studentmarks)
print("Average Marks of Student is",average)
s2.display()
Studentmarks =s2.getmarks()
average=sum(studentmarks)/len(studentmarks)
print("Average Marks of Student is",average)
s3.display()
studentmarks=s3.getmarks()
average=sum(studentmarks)/len(studentmarks)
print("Average Marks of Student is",average)
print(“Space taken by program is :”,getsizeof(name),getsizeof(rollno),getsizeof(marks))
print(“Time taken by program is ”,(time.time()-start_time)
OUTPUT :
Student details are :
Name is: Manju
Rollno is: 1
Marks of students are : [20, 25, 30]
Average marks of student is : 25.0
Student details are :
Name is: Pavan
Rollno is: 2
Marks of students are : [25, 20, 35]
Average marks of student is : 26.666666666666668
Student details are :
Name is: Manu
Rollno is: 3
Marks of students are : [30, 35, 40]
Average marks of student is : 35.0
Space taken by pgm is: 144
Time taken by pgm is : 0.0
2. Implement above solution using array and Compute space and time complexities and
compare two solutions.
import time
from sys import getsizeof
import array as arr
start_time = time.time()
name=["Manju","Aditya","Manu"]
rollno=arr.array('i',[1,2,3])
m1=arr.array('i',[20,25,30])
m2=arr.array('i',[25,20,35])
m3=arr.array('i',[30,35,40])
print("Student Details are")
for i in range(3):
print("Name:",name[i])
print("Roll Number:",rollno[i])
print("Marks of student are",m1[i],m2[i],m3[i])
average=(m1[i]+m2[i]+m3[i])/3
print("Average Marks of Student is",average)
print("space taken by program",
,getsizeof(name)+getsizeof(rollno)+getsizeof(m1)+getsizeof(m2)+getsizeof(m3))
print("time taken by program is",(time.time()-start_time))
OUTPUT :
Student Details are :
Name: Manju
Roll Number: 1
Marks of student are 20 25 30
Average Marks of Student is 25.0
Name: Aditya
Roll Number: 2
Marks of student are 25 20 35
Average Marks of Student is 26.666666666666668
Name: Manu
Roll Number: 3
Marks of student are 30 35 40
Average Marks of Student is 35.0
space taken by program 424
time taken by program is 0.0
WEEK-3
1. Implement Linear Search compute space and time complexities, plot graph using
asymptomatic notations.
import time
import random
import matplotlib.pyplot as plt
def linear(arr,target):
found=False
for i in range(len(arr)):
if arr[i]==target:
found=True
return found
arr=[25,50,30,60]
print("List :",arr)
target=int(input("Enter the key to search :"))
print(linear(arr,target))
sizes=[10,100,1000,10000]
linear_times=[]
for size in sizes:
start_time=time.time()
linear(arr.copy(),target)
linear_times.append(time.time()-start_time)
plt.plot(sizes,linear_times,label="Linear_search")
plt.xlabel("List sizes")
plt.ylabel("Time(seconds)")
plt.legend()
plt.show()
OUTPUT :
List : [25, 50, 30, 60]
Enter the key to search :50
True
2. Implement Bubble, Selection, insertion sorting algorithms compute space and time
complexities, plot graph using asymptomatic notations.
import random
import time
import matplotlib.pyplot as plt
# Bubble sort algorithm
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Selection sort algorithm
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Quicksort algorithm
def insertsort(arr):
n=len(arr)
for i in range(1, n-1):
k=arr[i]
j=i-1
while j>=0 and arr[j]>k:
arr[j+1]=arr[j]
j=j-1
arr[j+1]=k
# Generate lists of different sizes
sizes = [10, 100, 1000, 10000]
bubble_sort_times = []
selection_sort_times = []
insertsort_times = []
# Measure the time taken to sort each list using each algorithm
for size in sizes:
arr = [random.randint(1, 1000) for _ in range(size)]
start_time = time.time()
bubble_sort(arr.copy())
bubble_sort_times.append(time.time() - start_time)
start_time = time.time()
selection_sort(arr.copy())
selection_sort_times.append(time.time() - start_time)
start_time = time.time()
insertsort(arr.copy())
insertsort_times.append(time.time() - start_time)
# Generate a plot
plt.plot(sizes, bubble_sort_times, label="Bubble Sort")
plt.plot(sizes, selection_sort_times, label="Selection Sort")
plt.plot(sizes, insertsort_times, label="Insertion Sort")
plt.xlabel("List Size")
plt.ylabel("Time (Seconds)")
plt.legend()
plt.show()
OUTPUT :
WEEK-4
1. Implement Binary Search using recursion Compute space and time complexities,
plot graph using asymptomatic notations and compare two.
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
OUTPUT :
C:\Users\bvvsdff\DS\Scripts\python.exe "C:\Users\bvvsdff\Desktop\21CS018 IV
SEM\DS\Sort graph.py"
Element is present at index 3
2. Implement Merge and quick sorting algorithms compute space and time complexities
, plot graph using asymptomatic notations and compare all solutions.
import random
import time
import matplotlib.pyplot as plt
def mergesort(arr):
if len(arr) > 1:
mid = len(arr) // 2
sa1 = arr[:mid]
sa2 = arr[mid:]
mergesort(sa1)
mergesort(sa2)
i=j=k=0
while i < len(sa1) and j < len(sa2):
if sa1[i] < sa2[j]:
arr[k] = sa1[i]
i += 1
else:
arr[k] = sa2[j]
j += 1
k += 1
while i < len(sa1):
arr[k] = sa1[i]
i += 1
k += 1
while j < len(sa2):
arr[k] = sa2[j]
j += 1
k += 1
def quick_sort(arr):
if len(arr)<=1:
return arr
else:
pivot=arr[0]
left=[x for x in arr[1:]if x < pivot]
right=[x for x in arr[1:]if x >= pivot]
return quick_sort(left)+[pivot] +quick_sort(right)
sizes=[10,100,1000,10000]
mergesort_times=[]
quick_sort_times=[]
for size in sizes:
arr=[random.randint(1,1000) for _ in range(size)
start_time=time.time()
mergesort(arr.copy())
mergesort_times.append(time.time()-start_time)
start_time=time.time()
quick_sort(arr.copy())
quick_sort_times.append(time.time()-start_time)
plt.plot(sizes,mergesort_times,label="mergesort")
plt.plot(sizes,quick_sort_times,label="quick_sort")
plt.xlabel("list size")
plt.ylabel("time (second)")
plt.legend()
plt.show()
OUTPUT :
3. Implement Fibonacci sequence with dynamic programming.
def fib(n):
if n==0:
return 0
if n==1:
return +1
return fib(n-1)+fib(n-2)
print(fib(6))
OUTPUT :
C:\Users\bvvsdff\21CS032\Scripts\python.exe D:\21CS032\fibonic.py
8
WEEK-5
1. Implement Singly linked list (Traversing the Nodes, searching for a Node,
Prepending Nodes, Removing Nodes)
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# Traversing the Nodes
def traverse(self):
if self.head is None:
print("Linked list is empty")
else:
current_node = self.head
while current_node:
print(current_node.data, end=" ")
current_node = current_node.next
print()
# Searching for a Node
def search(self, value):
if self.head is None:
return False
current_node = self.head
while current_node:
if current_node.data == value:
return True
current_node = current_node.next
return False
# Prepending Nodes
def prepend(self, data):
new_node = Node(data, self.head)
self.head = new_node
# Removing Nodes
def remove(self, value):
if self.head is None:
return
if self.head.data == value:
self.head = self.head.next
return
current_node = self.head
while current_node.next:
if current_node.next.data == value:
current_node.next = current_node.next.next
return
current_node = current_node.next
# Create a linked list
ll = LinkedList()
# Add some nodes to the list
ll.head = Node(1)
ll.head.next = Node(2)
ll.head.next.next = Node(3)
# Traverse the list
ll.traverse() #output 1 2 3
# Search for a node
print(ll.search(2)) # Output: True
print(ll.search(4)) # Output: False
# Prepend a node
ll.prepend(0)
ll.traverse() # Output: 0 1 2 3
# Remove a node
ll.remove(2)
ll.traverse() # Output: 0 1 3
OUTPUT :
123
Week-6
1. Implement linked list Iterators.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def __iter__(self):
self.current_node = self.head
return self
def __next__(self):
if self.current_node is None:
raise StopIteration
else:
data = self.current_node.data
self.current_node = self.current_node.next
return data
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
for data in linked_list:
print(data)
OUTPUT:
"C:\Program Files\Python311\python.exe" "D:\21CS002\LINKED LIST.py"
Process finished with exit code
Week-7
1. Implement DLL.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def add_task(self, task):
new_node = Node(task)
if self.is_empty():
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
new_node.prev = current
def delete_task(self, task):
if self.is_empty():
print("Task manager is empty.")
return
current = self.head
while current is not None:
if current.data == task:
if current.prev is not None:
current.prev.next = current.next
else:
self.head = current.next
if current.next is not None:
current.next.prev = current.prev
print(f"Task '{task}' deleted.")
return
current = current.next
print(f"Task '{task}' not found.")
def display_tasks(self):
if self.is_empty():
print("Task manager is empty.")
return
current = self.head
print("Tasks:")
while current is not None:
print(current.data)
current = current.next
# Example usage
task_manager = DoublyLinkedList()
task_manager.add_task("Task 1")
task_manager.add_task("Task 2")
task_manager.add_task("Task 3")
task_manager.display_tasks()
task_manager.delete_task("Task 2")
task_manager.display_tasks()
task_manager.delete_task("Task 4")
OUTPUT :
D:\21CS032\venv\Scripts\python.exe D:\21CS032\SimpleAppofDLL.py
Tasks:
Task 1
Task 2
Task 3
Task 'Task 2' deleted.
Tasks:
Task 1
Task 3
Task 'Task 4' not found.
Process finished with exit code 0
2. Implement CDLL
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def insert(self, data):
new_node = Node(data)
if self.is_empty():
self.head = new_node
new_node.next = new_node
new_node.prev = new_node
else:
last_node = self.head.prev
last_node.next = new_node
new_node.prev = last_node
new_node.next = self.head
self.head.prev = new_node
def remove(self, data):
if self.is_empty():
return
current = self.head
prev_node = None
while True:
if current.data == data:
if current.next == current: # Single node in the list
self.head = None
else:
prev_node.next = current.next
current.next.prev = prev_node
if current == self.head: # Removing head node
self.head = current.next
return
prev_node = current
current = current.next
if current == self.head:
break
def display(self):
if self.is_empty():
print("Circular Doubly Linked List is empty.")
return
current = self.head
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.head:
break
print(current.data)
# Example usage
cdll = CircularDoublyLinkedList()
cdll.insert(5)
cdll.insert(10)
cdll.insert(15)
cdll.display() # Output: 5 -> 10 -> 15
cdll.remove(10)
cdll.display() # Output: 5 -> 15
OUTPUT :
C:\Users\isnewlba23\AppData\Local\Programs\Python\Python311\python.exe
5 -> 10 -> 15 -> 5
5 -> 15 -> 5
Week-8
1. Implement Stack Data Structure.
class stack:
def __init__(self,maxsize,top):
self.maxsize=maxsize
self.top=top
self.list=[]
def __str__(self):
values=self.list.reverse()
values=[str(x) for x in self.list]
return 'ln'.join(values)
def push(self,value):
if self.top==self.maxsize-1:
print("The stack is full")
else:
self.list.append(value)
self.top +=1
print(value,"push is done with successfully.")
def pop(self):
if self.top ==-1:
print("The stack is empty.")
else:
print("poped item=",self.list.pop())
self.top-=1
def display(self):
if self.top==-1:
print("The stack is empty")
else:
print("contents of the stack are ")
print(self)
stack=stack(5,-1)
stack.push(10)
stack.display()
stack.push(20)
stack.pop()
OUTPUT :
10 push is done with successfully.
contents of the stack are
10
20 push is done with successfully.
poped item= 20
2. Implement bracket matching using stack.
class BracketMatcher:
def __init__(self):
self.stack = []
def is_match(self, left_bracket, right_bracket):
if left_bracket == "(" and right_bracket == ")":
return True
elif left_bracket == "{" and right_bracket == "}":
return True
elif left_bracket == "[" and right_bracket == "]":
return True
else:
return False
def is_balanced(self, expression):
for char in expression:
if char in ["(", "{", "["]:
self.stack.append(char)
elif char in [")", "}", "]"]:
if len(self.stack) == 0:
return False
top_element = self.stack.pop()
if not self.is_match(top_element, char):
return False
return len(self.stack) == 0
# Example usage
matcher = BracketMatcher()
expression1 = "({[]})"
print(expression1, "is balanced:", matcher.is_balanced(expression1))
expression2 = "{[}]"
print(expression2, "is balanced:", matcher.is_balanced(expression2))
OUTPUT :
C:\Users\isnewlba23\AppData\Local\Programs\Python\Python311\python.exe
({[]}) is balanced: True
{[}] is balanced: False
Week-9
1. Program to demonstrate recursive operations ( Fibonacci)
def fib(n):
if n==0:
return 0
if n==1:
return +1
return fib(n-1)+fib(n-2)
print(fib(6))
OUTPUT :
C:\Users\bvvsdff\21CS032\Scripts\python.exe D:\21CS032\fibonic.py
8
2. Implement solution for Tower of Hanoi
CODE :
def tower_of_hanoi(n, source, target, auxiliary):
if n > 0:
# Move n-1 disks from source to auxiliary peg
tower_of_hanoi(n-1, source, auxiliary, target)
# Move the nth disk from source to target peg
print(f"Move disk {n} from {source} to {target}")
# Move the n-1 disks from auxiliary to target peg
tower_of_hanoi(n-1, auxiliary, target, source)
# Example usage
n = 3 # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B')
OUTPUT :
C:\Users\isnewlba23\AppData\Local\Programs\Python\Python311\python.exe
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Week-10
1. Implement Queue.
class queue:
def __init__(self):
self.queue_ds=[]
self.front=-1
self.rear=-1
def empty(self):
if len(self.queue_ds)==0:
return True
else:
return False
def enqueue(self,val):
self.queue_ds.append (val)
if self.front==-1:
self.front+=1
self.rear+=1
print(val,"is successfully inserted")
else:
self.rear+=1
print(val,"is successfully inserted")
def Dequeue(self):
if len(self.queue_ds)== 0:
print(" queue is empty")
return
else:
temp=self.queue_ds.pop(self.front)
print("deleted item=",temp)
self.rear-=1
if len(self.queue_ds)==0:
self.front=-1
self.rear=-1
return
def display(self):
if len(self.queue_ds)==0:
print("queue is empty..")
return
print("the contents of Queue are:")
if self.front == self.rear:
print(self.queue_ds[self.front],"<-- Front")
return
print(self.queue_ds[self.front]," <-- front")
i =self.front +1
while i<self.rear:
print(self.queue_ds[i])
i +=1
print(self.queue_ds[self.rear],"<-- Rear")
a = queue()
a.enqueue(10)
a.enqueue(20)
a.enqueue(30)
a.display()
a.Dequeue()
a.display()
OUTPUT :
10 is successfully inserted
20 is successfully inserted
30 is successfully inserted
the contents of Queue are:
10 <-- front
20
30 <-- Rear
deleted item= 10
the contents of Queue are:
20 <-- front
30 <-- Rear
2. Implement priority queue
CODE :
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def insert(self, item, priority):
heapq.heappush(self._queue, (priority, self._index, item))
self._index += 1
def remove(self):
if self._queue:
return heapq.heappop(self._queue)[-1]
else:
raise IndexError("Priority queue is empty")
def is_empty(self):
return len(self._queue) == 0
priority_queue = PriorityQueue()
priority_queue.insert("Task 1", 5)
priority_queue.insert("Task 2", 3)
priority_queue.insert("Task 3", 7)
while not priority_queue.is_empty():
task = priority_queue.remove()
print("Processing:", task)
OUTPUT :
C:\Users\isnewlba23\AppData\Local\Programs\Python\Python311\python.exe
Processing: Task 2
Processing: Task 1
Processing: Task 3
week-11
1. Implement Binary search tree and its operations using list.
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert method to create nodes
def insert(self,data):
if self.data is None:
data = self.data
return
if data == self.data:
return
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
#search method to compare the value with nodes
def search(self, key):
if key == self.data:
print(str(key) + " is Found")
return
if key < self.data:
if self.left:
self.left.search(key)
else:
print(str(key) + " Not Found")
else:
if self.right:
self.right.search(key)
else:
print(str(key) + " Not Found")
#INORDER TRAVERSAL
def Inorder(self):
if self.left:
self.left.Inorder() # Left subtree
print(self.data, end=",") # ROOT
if self.right:
self.right.Inorder() # Right subtree
# PREORDER TRAVERSAL
def Preorder(self):
print(self.data, end=",") # ROOT
if self.left:
self.left.Preorder() # Left subtree
if self.right:
self.right.Preorder() # Right subtree
# POSTORDER TRAVERSAL
def Postorder(self):
if self.left:
self.left.Postorder() # Left subtree
if self.right:
self.right.Postorder() # Right subtree
print(self.data, end=",") # ROOT
root = Node(54)
root.insert(34)
root.insert(46)
root.insert(12)
root.insert(23)
root.insert(5)
root.search(12)
root.search(76)
print("\nPreorder Traversal of Binary SearchTree:")
root.Preorder()
print("\nInorder Traversal of Binary Search Tree: ")
root.Inorder()
print("\nPostorder Traversal of Binary Search Tree:")
root.Postorder()
OUTPUT :
D:\21CS032\venv\Scripts\python.exe D:\21CS032\Sample2.py
12 is Found
76 Not Found
Preorder Traversal of Binary SearchTree:
54,34,12,5,23,46,
Inorder Traversal of Binary Search Tree:
12,34,54,
Postorder Traversal of Binary Search Tree:
5,23,12,46,34,54,
Process finished with exit code 0
Week-12
1. Implementations of BFS.
graph = {'5':['3','7'],'3':['2', '4'],'7':['8'],'2':[],
'4':['8'],'8':[]}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
OUTPUT :
Following is the Breadth-First Search
537248
Process finished with exit code 0
2. 1. Implementations of DFS.
graph = {'5':['3','7'],'3':['2', '4'],'7':['8'],'2':[],'4':['8'],'8':[]}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node, end = " ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("Following is the Depth-First Search")
dfs(visited, graph, '5')=
OUTPUT:
Following is the Depth-First Search
532487
Week-13
1. Implement Hash functions.
CODE :
class HashTable:
def __init__(self):
self.table = {}
def insert(self, key, value):
hash_value = hash(key)
self.table[hash_value] = value
def get(self, key):
hash_value = hash(key)
return self.table.get(hash_value)
def remove(self, key):
hash_value = hash(key)
if hash_value in self.table:
del self.table[hash_value]
hash_table = HashTable()
hash_table.insert("name", "John")
hash_table.insert("age", 25)
hash_table.insert("city", "New York")
print(hash_table.get("name")) # Output: John
print(hash_table.get("age")) # Output: 25
print(hash_table.get("city")) # Output: New York
hash_table.remove("age")
print(hash_table.get("age")) # Output: None
OUTPUT :
C:\Users\isnewlba23\AppData\Local\Programs\Python\Python311\python.exe
John
25
New York
None