Data Scirnce Lab Manual
Data Scirnce Lab Manual
LAB MANUAL
(R22A0583)
B. TECH
(II YEAR – I SEM)
(2024-25)
Vision
To acknowledge quality education and instill high patterns of discipline
making the students technologically superior and ethically strong which
involves the improvement in the quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of
infrastructure, outstanding technical and teaching expertise to establish
the students in to competent and confident engineers.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multi disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed
in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted
to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.
10. Write a python program to implement DFS & BFS graph traversal 47
Techniques.
11. Write a program to implement Binary Search Tree. 49
Program:
class Flower:
#Common base class for all Flowers
def init (self, petalName, petalNumber, petalPrice):
self.name = petalName
self.petals = petalNumber
self.price = petalPrice
def getName(self):
return self.name
def getPetals(self):
return self.petals
def getPrice(self):
return self.price
print ("\n")
Page 1
Data Structures Lab
Output:
Page 2
Data Structures Lab
Exercise Programs:
Page 3
Data Structures Lab
Exercise Programs:
Page 4
Data Structures Lab
2. Develop an inheritance hierarchy based upon a Polygon class that has abstract methods area( )
and perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, that extend this base
class, with the obvious meanings for the area( ) and perimeter( ) methods. Write a simple
program that allows users to create polygons of the various types and input their geometric
dimensions, and the program then outputs their area and perimeter.
Program:
from abc import abstractmethod, ABCMeta
import math
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 3)
self._perimeter = self.perimeter()
self._area = self.area()
def perimeter(self):
return(sum(self._side_lengths))
def area(self):
#Area of Triangle
s = self._perimeter/2
product = s
for i in self._side_lengths:
product*=(s-i)
return product**0.5
class Quadrilateral(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 4)
self._perimeter = self.perimeter()
Page 5
Data Structures Lab
self._area = self.area()
def perimeter(self):
return(sum(self._side_lengths))
def area(self):
class Pentagon(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 5)
self._perimeter = self.perimeter()
self._area = self.area()
def perimeter(self):
return((self._side_lengths) * 5)
def area(self):
#object of Triangle
t1 = Triangle([1,2,2])
print(t1.perimeter(), t1.area())
#object of Quadrilateral
q1 = Quadrilateral([1,1,1,1])
print(q1.perimeter(), q1.area())
#object of Pentagon
p1 = Pentagon(1)
print(p1.perimeter(), p1.area())
Output:
Page 6
Data Structures Lab
Exercise Programs:
Page 7
Data Structures Lab
Exercise Programs:
Page 8
Data Structures Lab
3. Write a python program to implement method overloading and method overriding.
Method Overloading
Method overloading is an OOPS concept which provides ability to have several methods
having the same name with in the class where the methods differ in types or number of
arguments passed.
Method overloading in its traditional sense (as defined above) as exists in other languages like
method overloading in Java doesn’t exist in Python.
In Python if you try to overload a function by having two or more functions having the same
name but different number of arguments only the last defined function is recognized, calling
any other overloaded function results in an error.
Since using the same method name again to overload the method is not possible in Python, so
achieving method overloading in Python is done by having a single method with several
parameters. Then you need to check the actual number of arguments passed to the method
and perform the operation accordingly.
Program:
class OverloadDemo:
# sum method with default as None for parameters
def sum(self, a=None, b=None, c=None):
# When three params are passed
if a!=None and b!=None and c!=None:
s = a + b + c
print('Sum = ', s)
# When two params are passed
elif a!=None and b!=None:
s = a + b
print('Sum = ', s)
od = OverloadDemo()
od.sum(7, 8)
od.sum(7, 8, 9)
Output:
Page 9
Data Structures Lab
Method overriding - Polymorphism through inheritance
Method overriding provides ability to change the implementation of a method in a child class
which is already defined in one of its super class. If there is a method in a super class and
method having the same name and same number of arguments in a child class then the child
class method is said to be overriding the parent class method.
When the method is called with parent class object, method of the parent class is executed.
When method is called with child class object, method of the child class is executed. So the
appropriate overridden method is called based on the object type, which is an example of
Polymorphism.
Program:
class Person:
def init (self, name, age):
self.name = name
self.age = age
def displayData(self):
print('In parent class displayData method')
print(self.name)
print(self.age)
class Employee(Person):
def init (self, name, age, id):
# calling constructor of super class
super(). init (name, age)
self.empId = id
def displayData(self):
print('In child class displayData method')
print(self.name)
print(self.age)
print(self.empId)
Output:
P a g e 10
Data Structures Lab
Exercise Programs:
P a g e 11
Data Structures Lab
Exercise Programs:
P a g e 12
Data Structures Lab
P a g e 13
Data Structures Lab
4. Write a program for Linear Search and Binary search
Output:
P a g e 14
Data Structures Lab
Binary Search Program:
def binarySearch(target, List):
left = 0
right = len(List) - 1
global iterations
iterations = 0
Output:
P a g e 15
Data Structures Lab
Exercise Programs:
P a g e 16
Data Structures Lab
Exercise Programs:
P a g e 17
Data Structures Lab
5. Write a program to implement Bubble Sort and Selection Sort
Output:
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
Output:
P a g e 18
Data Structures Lab
Exercise Programs:
P a g e 19
Data Structures Lab
Exercise Programs:
P a g e 20
Data Structures Lab
6. Write a program to implement Merge sort and Quick sort
Output:
P a g e 21
Data Structures Lab
Quick Sort Program:
while True:
while (i <= j and alist[i] <= pivot):
i = i + 1
while (i <= j and alist[j] >= pivot):
j = j - 1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
Output:
P a g e 22
Data Structures Lab
Exercise Programs:
P a g e 23
Data Structures Lab
Exercise Programs:
P a g e 24
Data Structures Lab
7. Write a program to implement Stacks and Queues
Stack Program:
P a g e 25
Data Structures Lab
# Function to check if the stack is full or not
def isFull(self):
return self.size() == self.capacity
stack = Stack(3)
Output:
P a g e 26
Data Structures Lab
P a g e 27
Data Structures Lab
Queue Program:
# Initialize queue
def init (self, size):
self.q = [None] * size # list to store queue elements
self.capacity = size # maximum capacity of the queue
self.front = 0 # front points to the front element in the queue
self.rear = -1 # rear points to the last element in the queue
self.count = 0 # current size of the queue
return self.q[self.front]
P a g e 28
Data Structures Lab
# Function to check if the queue is empty or not
def isEmpty(self):
return self.size() == 0
q.append(1)
q.append(2)
q.append(3)
q.pop()
q.pop()
if q.isEmpty():
print("The queue is empty")
else:
print("The queue is not empty")
Output:
P a g e 29
Data Structures Lab
Exercise Programs:
P a g e 30
Data Structures Lab
Exercise Programs:
P a g e 31
Data Structures Lab
Exercise Programs:
P a g e 32
Data Structures Lab
8. Write a program to implement Singly Linked List
Program:
import os
from typing import NewType
class _Node:
'''
Creates a Node with two fields:
1. element (accesed using ._element)
2. link (accesed using ._link)
'''
slots = '_element', '_link'
class LinkedList:
'''
Consists of member funtions to perform different
operations on the linked list.
'''
def isempty(self):
'''
Returns True if linked list is empty, otherwise False.
'''
return self._size == 0
P a g e 33
Data Structures Lab
Adds the passed element at the end of the linked list.
'''
newest = _Node(e, None)
if self.isempty():
self._head = newest
else:
self._tail._link = newest
self._tail = newest
self._size += 1
if self.isempty():
self._head = newest
self._tail = newest
else:
newest._link = self._head
self._head = newest
self._size += 1
i = index - 1
p = self._head
if self.isempty():
self.addFirst(e)
else:
for i in range(i):
p = p._link
newest._link = p._link
p._link = newest
print(f"Added Item at index {index}!\n\n")
self._size += 1
def removeFirst(self):
'''
Removes element from the beginning of the linked list.
Returns the removed element.
'''
if self.isempty():
print("List is Empty. Cannot perform deletion
operation.")
return
P a g e 34
Data Structures Lab
e = self._head._element
self._head = self._head._link
self._size = self._size - 1
if self.isempty():
self._tail = None
return e
def removeLast(self):
'''
Removes element from the end of the linked list.
Returns the removed element.
'''
if self.isempty():
print("List is Empty. Cannot perform deletion
operation.")
return
p = self._head
if p._link == None:
e = p._element
self._head = None
else:
while p._link._link != None:
p = p._link
e = p._link._element
p._link = None
self._tail = p
self._size = self._size - 1
return e
if index == 0:
return self.removeFirst()
elif index == self._size - 1:
return self.removeLast()
else:
for x in range(i):
p = p._link
e = p._link._element
p._link = p._link._link
self._size -= 1
return e
def display(self):
'''
P a g e 35
Data Structures Lab
Utility function to display the linked list.
'''
if self.isempty() == 0:
p = self._head
while p:
print(p._element, end='-->')
p = p._link
print("NULL")
else:
print("Empty")
###################################################################
def options():
'''
Prints Menu for operations
'''
options_list = ['Add Last', 'Add First', 'Add Anywhere',
'Remove First', 'Remove Last', 'Remove Anywhere',
'Display List', 'Print Size', 'Search', 'Exit']
print("MENU")
for i, option in enumerate(options_list):
print(f'{i + 1}. {option}')
def switch_case(choice):
'''
Switch Case for operations
'''
if choice == 1:
elem = int(input("Enter Item: "))
L.addLast(elem)
print("Added Item at Last!\n\n")
elif choice == 2:
elem = int(input("Enter Item: "))
L.addFirst(elem)
print("Added Item at First!\n\n")
P a g e 36
Data Structures Lab
elif choice == 3:
elem = int(input("Enter Item: "))
index = int(input("Enter Index: "))
L.addAnywhere(elem, index)
elif choice == 4:
print("Removed Element from First:", L.removeFirst())
elif choice == 5:
print("Removed Element from last:", L.removeLast())
elif choice == 6:
index = int(input("Enter Index: "))
print(f"Removed Item: {L.removeAnywhere(index)} !\n\n")
elif choice == 7:
print("List: ", end='')
L.display()
print("\n")
elif choice == 8:
print("Size:", len(L))
print("\n")
elif choice == 9:
key = int(input("Enter item to search: "))
if L.search(key) >= 0:
print(f"Item {key} found at index position
{L.search(key)}\n\n")
else:
print("Item not in the list\n\n")
###################################################################
Output:
P a g e 37
Data Structures Lab
Signature of the Faculty
P a g e 38
Data Structures Lab
Exercise Programs:
P a g e 39
Data Structures Lab
Exercise Programs:
P a g e 40
Data Structures Lab
9. Write a program to implement Doubly Linked list
Program:
import os
class _Node:
'''
Creates a Node with three fields:
1. element (accessed using ._element)
2. link (accessed using ._link)
3. prev (accessed using ._prev)
'''
slots = '_element', '_link', '_prev'
class DoublyLL:
'''
Consists of member funtions to perform different
operations on the doubly linked list.
'''
def isempty(self):
'''
Returns True if doubly linked list is empty, otherwise False.
'''
return self._size == 0
if self.isempty():
self._head = newest
else:
self._tail._link = newest
newest._prev = self._tail
self._tail = newest
self._size += 1
if self.isempty():
self._head = newest
self._tail = newest
else:
newest._link = self._head
self._head._prev = newest
self._head = newest
self._size += 1
def removeFirst(self):
'''
Removes element from the beginning of the doubly linked list.
Returns the removed element.'''
P a g e 42
Data Structures Lab
if self.isempty():
print('List is already empty')
return
e = self._head._element
self._head = self._head._link
self._size -= 1
if self.isempty():
self._tail = None
else:
self._head._prev = None
return e
def removeLast(self):
'''
Removes element from the end of the doubly linked list.
Returns the removed element.
'''
if self.isempty():
print("List is already empty")
return
e = self._tail._element
self._tail = self._tail._prev
self._size -= 1
if self.isempty():
self._head = None
else:
self._tail._link = None
return e
P a g e 43
Data Structures Lab
def display(self):
'''
Utility function to display the doubly linked list.
'''
if self.isempty():
print("List is Empty")
return
p = self._head
print("NULL<-->", end='')
while p:
print(p._element, end="<-->")
p = p._link
print("NULL")
###################################################################
def options():
'''
Prints Menu for operations
'''
options_list = ['Add Last', 'Add First', 'Add Anywhere',
'Remove First', 'Remove Last', 'Remove Anywhere',
'Display List', 'Exit']
print("MENU")
for i, option in enumerate(options_list):
print(f'{i + 1}. {option}')
def switch_case(choice):
'''
Switch Case for operations
'''
os.system('cls')
if choice == 1:
elem = int(input("Enter Item: "))
DL.addLast(elem)
print("Added Item at Last!\n\n")
elif choice == 2:
elem = int(input("Enter Item: "))
DL.addFirst(elem)
print("Added Item at First!\n\n")
elif choice == 3:
elem = int(input("Enter Item: "))
index = int(input("Enter Index: "))
DL.addAnywhere(elem, index)
P a g e 44
Data Structures Lab
elif choice == 4:
print("Removed Element from First:", DL.removeFirst())
elif choice == 5:
print("Removed Element from last:", DL.removeLast())
elif choice == 6:
index = int(input("Enter Index: "))
print(f"Removed Item: {DL.removeAnywhere(index)} !\n\n")
elif choice == 7:
print("List:")
DL.display()
print("\n")
elif choice == 8:
import sys
sys.exit()
###################################################################
Output:
P a g e 45
Data Structures Lab
10. Write a python program to implement DFS & BFS graph traversal Techniques Dat
Breadth First Search Traversal: a res Lab 2020
# Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
# Constructor
def init (self):
while queue:
# Driver code
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3) P a g e 46
Data Structures Lab
g.addEdge(3, 3)
Output:
# Constructor
def init (self):
# Driver's code
if name == " main ":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
# Function call
g.DFS(2)
Output:
P a g e 48
Data Structures Lab
Signature of the Faculty
P a g e 49
Data Structures Lab
11.Write a program to implement Binary Search Tree
Program:
def insert(self,val):
# check if there is no root
if (self.val == None):
self.val = val
# check where to insert
else:
# check for duplicate then stop and return
if val == self.val: return 'no duplicates allowed in binary search tree'
# check if value to be inserted < currentNode's value
if (val < self.val):
# check if there is a left node to currentNode if true then recurse
if(self.left):
self.left.insert(val)
# insert where left of currentNode when currentNode.left=None
else: self.left = binarySearchTree(val)
# same steps as above here the condition we check is value to be
# inserted > currentNode's value
else:
if(self.right):
self.right.insert(val)
else: self.right = binarySearchTree(val)
def breadthFirstSearch(self):
currentNode = self
bfs_list = []
queue = []
queue.insert(0,currentNode)
while(len(queue) > 0):
currentNode = queue.pop()
bfs_list.append(currentNode.val)
if(currentNode.left):
queue.insert(0,currentNode.left)
if(currentNode.right):
queue.insert(0,currentNode.right)
return bfs_list
# In order means first left child, then parent, at last right child
def depthFirstSearch_INorder(self):
return self.traverseInOrder([])
P a g e 50
Data Structures Lab
# Pre order means first parent, then left child, at last right child
def depthFirstSearch_PREorder(self):
return self.traversePreOrder([])
# Post order means first left child, then right child , at last parent
def depthFirstSearch_POSTorder(self):
return self.traversePostOrder([])
P a g e 51
Data Structures Lab
# if len(nodes_effected)==1 means, the node to be deleted doesn't
# have any children
# so we can just check from its parent node the position(left or
# right) of node we want to delete
# and point the position to 'None' i.e node is deleted
if (len(nodes_effected)==1):
if (parent_node.left.val == deleteing_node.val) : parent_node.left = None
else: parent_node.right = None
return 'Succesfully deleted'
# if len(nodes_effected) > 1 which means the node we are
# going to delete has 'children',
# so the tree must be rearranged from the deleteing_node
else:
# if the node we want to delete doesn't have any parent
# means the node to be deleted is 'root' node
if (parent_node == None):
nodes_effected.remove(deleteing_node.val)
# make the 'root' nodee i.e self value,left,right to None,
# this means we need to implement a new tree again without
# the deleted node
self.left = None
self.right = None
self.val = None
bst = binarySearchTree()
bst.insert(7)
bst.insert(4)
bst.insert(9)
bst.insert(0)
bst.insert(5)
bst.insert(8)
bst.insert(13)
P a g e 52
Data Structures Lab
# 7
# / \
# / \
# 4 9
# / \ / \
# 0 5 8 13
print(bst.delete(5))
print(bst.delete(9))
print(bst.delete(7))
# after deleting
print('IN order: ',bst.depthFirstSearch_INorder())
print('PRE order:' ,bst.depthFirstSearch_PREorder())
print('POST order:', bst.depthFirstSearch_POSTorder())
Output:
P a g e 53
Data Structures Lab
12.Write a program for implementing B+ Tree
import math
# Node creation
class Node:
def init (self, order):
self.order = order
self.values = []
self.keys = []
self.nextKey = None
self.parent = None
self.check_leaf = False
else:
elif (i + 1 == len(temp1)): self.values.append(value)
self.keys.append([key]) break
# B plus tree
class BplusTree:
def init (self, order):
self.root = Node(order)
self.root.check_leaf = True
# Insert operation
def insert(self, value, key):
value = str(value)
old_node = self.search(value)
old_node.insert_at_leaf(old_node, value, key)
if (len(old_node.values) == old_node.order):
node1 = Node(old_node.order)
node1.check_leaf = True
node1.parent = old_node.parent
mid = int(math.ceil(old_node.order / 2)) - 1
P a g e 54
Data Structures Lab
node1.values = old_node.values[mid + 1:]
node1.keys = old_node.keys[mid + 1:]
node1.nextKey = old_node.nextKey
old_node.values = old_node.values[:mid + 1]
old_node.keys = old_node.keys[:mid + 1]
old_node.nextKey = node1
self.insert_in_parent(old_node, node1.values[0], node1)
P a g e 55
Data Structures Lab
# Inserting at the parent
def insert_in_parent(self, n, value, ndash):
if (self.root == n):
rootNode = Node(n.order)
rootNode.values = [value]
rootNode.keys = [n, ndash]
self.root = rootNode
n.parent = rootNode
ndash.parent = rootNode
return
Data Structures Lab 2023-
parentNode = n.parent temp3 = parentNode.keys
for i in range(len(temp3)):
if (temp3[i] == n):
parentNode.values = parentNode.values[:i] + \
[value] + parentNode.values[i:]
parentNode.keys = parentNode.keys[:i +1] + [ndash]
+ parentNode.keys[i + 1:]
if (len(parentNode.keys) > parentNode.order):
parentdash = Node(parentNode.order)
parentdash.parent = parentNode.parent
mid = int(math.ceil(parentNode.order / 2)) - 1
parentdash.values = parentNode.values[mid + 1:]
parentdash.keys = parentNode.keys[mid + 1:]
value_ = parentNode.values[mid]
if (mid == 0):
parentNode.values = parentNode.values[:mid +1]
else:
parentNode.values = parentNode.values[:mid]
parentNode.keys = parentNode.keys[:mid + 1]
for j in parentNode.keys:
j.parent = parentNode
for j in parentdash.keys:
j.parent = parentdash
self.insert_in_parent(parentNode, value_,
parentdash)
P a g e 56
Data Structures Lab
if (flag == 0):
lev_leaf = lev
leaf = x
Data Structures Lab 2023-2024
flag = 1
record_len = 3
bplustree = BplusTree(record_len)
bplustree.insert('5', '33')
bplustree.insert('15', '21')
bplustree.insert('25', '31')
bplustree.insert('35', '41')
bplustree.insert('45', '10')
printTree(bplustree)
if(bplustree.find('5', '34')):
print("Found")
else:
print("Not found")
Output:
P a g e 57
Data Structures Lab
P a g e 58
Data Structures Lab
P a g e 59
Data Structures Lab
P a g e 60
Data Structures Lab