R22 - Data Structures and It's Applications Lab
R22 - Data Structures and It's Applications Lab
asd
asd
PROGRAM OUTCOMES
A B.Tech –graduate should possess the following program outcomes.
PROGRAM OBJECTIVES
WEEK 1:
Write a Python program for class, Flower, that has three instance variables of typestr, int, and
float, that respectively represent the name of the flower, its number of petals, and its price. Your
class must include a constructor method that initializes each variable to an appropriate value,
and your class should include methods for setting the value of each type, and retrievingthe value
of each type.
WEEK 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.
WEEK 3:
a) Write a Python program to implement method overloading.
WEEK 5:
WEEK 6:
WEEK 7:
WEEK 8:
WEEK 9:
WEEK 10:
WEEK 11:
WEEK 12:
1. Examine Python syntax and semantics and apply Python flow control and functions.
2. Create, run and manipulate Python Programs using core data structures like Lists.
5. Master object-oriented programming to create an entire python project using objects and
classes.
CONTENTS
1. Students should bring lab Manual/Record for every laboratory session and should
enter the readings /observations in the manual while performing the experiment.
2. The group- wise division made in the beginning should be adhered to, and no mix
up of students among different groups will be permitted later.
3. The components required pertaining to the experiment should be collected from
stores in –charge after duly filling in the requisition form.
4. When the experiment is completed, students should disconnect the setup made
by them, and should return all the components/instruments taken for the purpose.
5. Any damage to the apparatus that occurs during the experiment should be brought
to the notice of lab in-charge, consequently, the cost of repair or new apparatus
should be brought by the students.
11. Every student should keep his/her work area properly before leaving the
laboratory.
B TECH I YEAR II SEMESTER DATA STRUCTURES AND its APPLICATIONS LAB
PROGRAM-1 Date:
Aim:
Write a Python program for class, Flower, that has three instance variables of type str, int, and
float, that respectively represent the name of the flower, its number of petals, and its price.
Your class must include a constructor method that initializes each variable to an appropriate
value, and your class should include methods for setting the value of each type, and retrieving
the value of each type.
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")
Output:
Record Notes
PROGRAM-2 Date:
Aim:
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()
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:
Record Notes
PROGRAM-3 Date:
Aim:
Write a python program to implement method overloading.
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
passedelif a!=None and
b!=None:
s = a + b
print('Sum = ',
s)
od = OverloadDemo()
od.sum(7, 8)
od.sum(7, 8, 9)
Output:
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
classsuper(). 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:
Record Notes
PROGRAM-4 Date:
Aim:
Write a Python program to illustrate the following comprehensions:
a) List Comprehensions:
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:
output_list = [output_exp for var in input_list if (var satisfies this condition)]
Note that list comprehension may or may not contain an if condition. List comprehensions
can contain multiple for (nested list comprehensions).
Example: Suppose we want to create an output list which contains only the even numbers
which are present in the input list. Let’s see how to do this using for loop and list
comprehension and decide which method suits better.
Using Loop:
#Constructing output list WITHOUT using List comprehensions
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
Output:
input_list = [1, 2, 3, 4, 4, 5, 6, 7,
7]
comprehensions:",list_using_comp)
Output:
a) Dictionary Comprehensions:
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
Example 1: Suppose we want to create an output dictionary which contains only the odd
numbers that are present in the input list as keys and their cubes as values. Let’s see how
to do this using for loops and dictionary comprehension.
Using Loop:
input_list = [1, 2, 3, 4, 5, 6,
7]output_dict = {}
Output:
dictionaryinput_list =
[1,2,3,4,5,6,7]
Output:
Example 2: Given two lists containing the names of states and their corresponding
capitals, construct a dictionary which maps the states with their respective capitals. Let’s
see how to do this using for loops and dictionary comprehension.
Using Loop:
state = ['Gujarat', 'Maharashtra',
'Rajasthan']capital = ['Gandhinagar',
'Mumbai', 'Jaipur']
output_dict = {}
Output:
Output:
c) Set Comprehensions:
Set comprehensions are pretty similar to list comprehensions. The only difference between
them is that set comprehensions use curly brackets { }. Let’s look at the following
example to understand set comprehensions.
Example : Suppose we want to create an output set which contains only the even numbers
that are present in the input list. Note that set will discard all the duplicate values. Let’s
see how we can do this using for loops and set comprehension.
Using Loop:
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
Output:
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
comprehensions:",set_using_comp)
Output:
d) Generator Comprehensions:
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output:
Record Notes
PROGRAM-5 Date:
Aim:
Write a python program for Linear Search .
Linear Search Program:
def linearSearch(target, List):
position = 0
global iterations
iterations = 0
while position < len(List):
iterations += 1
if target == List[position]:
return position
position += 1
return -1
Output:
left = 0
right = len(List) - 1
global iterations
iterations = 0
Output:
Record Notes
PROGRAM-6 Date:
Aim:
Write a python program to implement Bubble Sort
Output:
Output:
Record Notes
PROGRAM-7 Date:
Aim:
Output:
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:
Record Notes
PROGRAM-8 Date:
Aim:
a) Write a python program to implement Stacks
Stack Program:
stack = Stack(3)
Output:
# 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]
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:
Record Notes
PROGRAM-9 Date:
Aim:
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
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
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):
'''
###################################################################
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")
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:
Record Notes
PROGRAM-10 Date:
Aim:
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.
'''
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
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)
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:
Record Notes
PROGRAM-11 Date:
Aim:
Write a program to implement Breadth First Search
Program:
# Constructor
def init (self):
while queue:
# Driver code
Output:
Record Notes
PROGRAM-12 Date:
Aim:
Write a program to implement Depth First Search
Program:
class Graph:
# Constructor
def init (self):
# Driver code
Output :
Record Notes