DSAP Lab Manual PDF
DSAP Lab Manual PDF
GITAM
(Deemed to be University 3U/S of UGC and Accredited by NAAC with 'A+ ' Grade)
Gandhi Nagar
Visakhapatnam-530045
DATA STRUCTURES AND ALGORITHMS WITH PYTHON LABORATORY
INDEX
List of Practical Experiments:
• Student class with data members student rollno, name,address, course. Include a constructor to initialize data
members. Add a method to print the student details.
• Book class with data members book_id,name,cost and publisher. Include constructor and a method to display
the book details. Create 3 objects and display their details.
• Account class with data members acc_no,name,balance. Include a constructor and methods to perform deposit
and withdraw operations on account. Create account object perform some operations and display the account
details.
• Product class with data members product_id, product_name, price, expiry_date. Include constructor to
initialize data members and a method to print products details.
• Complex_Number with data members real_part and imaginary_part. Include constructor to initialize complex
number. Add a method which adds two complex numbers.
• Employee class with data members eno,ename,sal,designation. Include constructor to initialize employee
details and count the number of employee objects created.
2. Create a class called Distance. A person has to travel a certain distace and he used two cars. Now create two
objects “cardist1” and “cardist2” for the class Distance. Add the two objects distances and put the total distance in the
third object of class Distance “totaldist”. Take one data member, which will accept the distance input in km. Take two
functions, for accepting the distance and the other for displaying. Display the total distance in meters.
Course Outcomes:
After Completion of this course, the student will be able to:
● Explain various ways of representing data in a computer (L2)
● Demonstrate operations on linear data structures (L2)
● Illustrate the mechanisms for creating, altering and traversing various types of trees (L2)
● Explain the representations, traversals and applications of graphs (L2)
● Analyze common sorting algorithms (L4)
● Choose a data structure that gives the best performance for a given application(L6)
1. Write a program to create
a) Student class with data members student rollno, name,address, course. Include a constructor to initialize
data members. Add a method to print the student details.
class Student:
rollno = 0
name = ""
address = ""
course = ""
def __init__(self,rollno,name,address,course):
self.rollno = rollno
self.name = name
self.address = address
self.course = course
def printDetails(self):
print(self.name,"(Roll no:",self.rollno,"), lives in/at",self.address,"and is enr
olled in",self.course)
student1 = Student(122010404027,"Abhishek","Vizag","ECE(AI&ML)")
student1.printDetails()
Output:
Abhishek (Roll no: 122010404027 ), lives in/at Vizag and is enrolled in ECE(AI&ML)
b) Book class with data members book_id,name,cost and publisher. Include constructor and a method to
display the book details. Create 3 objects and display their details.
class Book:
bookid = ""
name = ""
cost = 0
publisher = ""
def __init__(self,bookid,name,cost,publisher):
self.bookid = bookid
self.name = name
self.cost = cost
self.publisher = publisher
def showDetails(self):
print(self.bookid,self.name,": ₹",self.cost,"from",self.publisher)
Output:
978-1408855652 Harry Potter and the Philosopher's Stone: ₹ 309 from Bloomsbury
978-0141346809 Percy Jackson and the Lightning Thief: ₹ 283 from Penguin
978-0141324906 Diary Of A Wimpy Kid : ₹ 251 from Penguin
c) Account class with data members acc_no,name,balance. Include a constructor and methods to perform
deposit and withdraw operations on account. Create account object perform some operations and
display the account details.
class Account:
acc_no = 0
name = ""
balance = 0
def __init__(self,acc_no,name,balance):
self.acc_no = acc_no
self.name = name
self.balance = balance
def deposit(self,amount):
self.balance += amount
def withdraw(self,amount):
self.balance -= amount
myAccount = Account(100,"Abhishek",100000)
print(myAccount.balance)
myAccount.deposit(50000)
print(myAccount.balance)
myAccount.withdraw(25000)
print(myAccount.balance)
Output:
100000
150000
125000
d) Product class with data members product_id, product_name, price, expiry_date. Include constructor to
initialize data members and a method to print products details.
class Product:
product_id = 0
product_name = ""
price = 0
expiry_date = ""
def __init__(self,product_id,product_name,price,expiry_date):
self.product_id = product_id
self.product_name = product_name
self.price = price
self.expiry_date = expiry_date
def showProductDetails(self):
print("ID:",self.product_id,self.product_name,"₹",self.price,". Use by:",self.exp
iry_date)
noodles = Product(1,"Maggi",10,"31/12/2022")
biscuit = Product(2,"Hide & Seek",25,"4/4/2023")
cake = Product(3,"Chocolate Cake",100,"12/12/2022")
noodles.showProductDetails()
biscuit.showProductDetails()
cake.showProductDetails()
Output:
ID: 1 Maggi ₹ 10 . Use by: 31/12/2022
ID: 2 Hide & Seek ₹ 25 . Use by: 4/4/2023
ID: 3 Chocolate Cake ₹ 100 . Use by: 12/12/2022
e) Complex_Number with data members real_part and imaginary_part. Include constructor to initialize
complex number. Add a method which adds two complex numbers.
class ComplexNumber:
real_part = 0
imaginary_part = 0
def __init__(self,real_part,imaginary_part):
self.real_part = real_part
self.imaginary_part = imaginary_part
def add(a,b):
c = ComplexNumber(0,0)
c.real_part = a.real_part + b.real_part
c.imaginary_part = a.imaginary_part + b.imaginary_part
return c
a = ComplexNumber(3,4)
b = ComplexNumber(4,5)
sum = add(a,b)
print(sum.real_part,"+ i",sum.imaginary_part)
Output:
7 + i 9
f) Employee class with data members eno,ename,sal,designation. Include constructor to initialize employee
details and count the number of employee objects created.
class Count():
c = 0
count = Count()
class Employee:
eno = 0
ename = ""
sal = 0
designation = ""
def __init__(self,eno,ename,sal,designation):
self.eno = eno
self.ename = ename
self.sal = sal
self.designation = designation
count.c += 1
Output:
3
2. Create a class called Distance. A person has to travel a certain distace and he used two cars. Now create
two objects “cardist1” and “cardist2” for the class Distance. Add the two objects distances and put the total
distance in the third object of class Distance “totaldist”. Take one data member, which will accept the distance
input in km. Take two functions, for accepting the distance and the other for displaying. Display the total
distance in meters.
class Distance:
distance = 0
def inputDistance(self):
self.distance = input("Enter the distance in km:")
def showDistance(self):
print(self.distance)
cardist1 = Distance()
cardist1.inputDistance()
cardist2 = Distance()
cardist2.inputDistance()
totaldist = Distance()
totaldist.distance = str(int(cardist1.distance)+int(cardist2.distance))
print("Total distance=",int(totaldist.distance)*1000,"m") # converting km to m
Output:
Enter the distance in km:5
Enter the distance in km:7
Total distance= 12000 m
# Single inheritence
class Apple:
manufacturer = 'Apple Inc'
contact_website = 'www.apple.com/contact'
name = 'Apple'
def contact_details(self):
print('Contact us at ', self.contact_website)
class MacBook(Apple):
def __init__(self):
self.year_of_manufacture = 2018
def manufacture_details(self):
print('This MacBook was manufactured in {0}, by {1}.'
.format(self.year_of_manufacture, self.manufacturer))
macbook = MacBook()
macbook.manufacture_details()
# Multiple inheritence
class OperatingSystem:
multitasking = True
name = 'Mac OS'
mactower = MacTower()
# Multilevel inheritence
class MusicalInstrument:
num_of_major_keys = 12
class StringInstrument(MusicalInstrument):
type_of_wood = 'Tonewood'
class Guitar(StringInstrument):
def __init__(self):
self.num_of_strings = 6
print('The guitar consists of {0} strings,' +
'it is made of {1} and can play {2} keys.'
.format(self.num_of_strings,
self.type_of_wood, self.num_of_major_keys))
guitar = Guitar()
Output:
This MacBook was manufactured in 2018, by Apple Inc.
Multitasking system
Name: Mac OS
The guitar consists of {0} strings,it is made of Tonewood and can play 12 keys.
Output:
TutorialsPoint
Tutorials Point
# Driver's code
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))
Output:
Addition is : (3+5j)
5.Develop a program to overload “area” method to calculate area of different polygon shapes.
# Program for calculating the area of a shapes/polygon
def calculate_area(name):\
else:
print("Sorry! This shape is not available")
# driver code
if __name__ == "__main__" :
# function calling
calculate_area(shape_name)
Output:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 3
Enter rectangle's breadth: 5
The area of rectangle is 15.
6)Write a program to Perform Linear Search on an array.
Output:
Case1:
Enter the list of numbers: 4 56 62 73 81 9 17 5
The number to search for: 73
73 was found at index 3.
Case2:
Enter the list of numbers: 4 2 7 9 11 77
The number to search for: 33
33 was not found.
Output:
Enter the sorted list of numbers: 21 45 57 62 81 93
The number to search for: 45
45 was found at index 1.
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Constructor
def __init__(self):
self.value = "Inside Child"
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
9. Develop a program to implement various sorting techniques
a) Insertion sort
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)
Output:
[19, 2, 31, 45, 30, 11, 27, 121]
b) Selection Sort
#Selection Sort program
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]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 32 13 28 39 1 5 72 57
Sorted list: [1, 5, 13, 28, 32, 39, 57, 72]
c)Bubble Sort
Output:
[2, 5, 11, 19, 20, 31, 33, 62, 100]
10. Design a program to create a singly linked list for the following operations
# Node class
class Node:
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
Output:
Created Single linked list is:
17864
# Node class
class Node:
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
temp = None
# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
Output:
Created Single Linked List:
2317
# Node class
class Node:
# Assign data
self.data = data
# Data found
return True
current = current.next
# Driver code
if __name__ == '__main__':
Output:
Item found
11. Design a program to create a doubly linked list for the following operations
a)Insert a Node at Beginning, at Ending and at a given Position and display
# A program to demonstrate all insertion methods of DLL
class Node:
class DoublyLinkedList:
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 1. Allocates node
# 2. Put in the data
new_node = Node(new_data)
return
# Driver code
# Start with empty list
if __name__ == "__main__":
llist = DoublyLinkedList()
# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)
Output:
DLL after Insertion is:
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# Base Case
if self.head is None or dele is None:
return
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
Output:
Original Double Linked List 30 10 8 4 2
Double Linked List after deletion 10 2
12. Create a Circular singly linked list for adding and deleting a Node.
a) #Circular singly linked list add at beg,end,after
class Node:
def __init__(self, data):
self.data = data
self.next = 0
class CircularLinkedList:
def __init__(self):
self.last = None
if (self.last == None):
return None
temp = Node(data)
p = self.last.next
while p:
if (p.data == item):
temp.next = p.next
p.next = temp
if (p == self.last):
self.last = temp
return self.last
else:
return self.last
p = p.next
if (p == self.last.next):
print(item, "not present in the list")
break
def traverse(self):
if (self.last == None):
print("List is empty")
return
temp = self.last.next
while temp:
print(temp.data, end=" ")
temp = temp.next
if temp == self.last.next:
break
# Driver Code
if __name__ == '__main__':
llist = CircularLinkedList()
last = llist.addToEmpty(6)
last = llist.addBegin(4)
last = llist.addBegin(2)
last = llist.addEnd(8)
last = llist.addEnd(12)
last = llist.addAfter(15, 2)
print("Circular Linked list")
llist.traverse()
Output:
Circular Linked list
2 15 4 6 8 12
b)# Python program to delete a given key from Circular linked list.
# Node of a doubly linked list
class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data
else:
ptr1.next = ptr1 # For the first node
head_ref = ptr1
return head_ref
temp = head
if (head != None) :
while(True) :
print( temp.data, end = " ")
temp = temp.next
if (temp == head):
break
print()
head = None
last = head
d = None
# If head is to be deleted
if((head).data == key) :
else:
print("no such keyfound")
return head
# Driver code
# Initialize lists as empty
head = None
head = deleteNode(head, 7)
Output:
List Before Deletion:
10 8 7 5 2
List After Deletion:
10 8 5 2
class Stack:
def __init__(self):
self.stack = []
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
AStack.add("Fri")
AStack.add("Sat")
print(AStack.peek())
Output:
Tue
Sat
class Stack:
def __init__(self):
self.stack = []
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
Output:
Thu
Wed
class Conversion:
# An operator is encountered
else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)
print("".join(self.output))
# Driver's code
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
# Function call
obj.infixToPostfix(exp)
Output:
abcd^e-fgh*+^*+i-
15. Perform String reversal using stack
# Python program to reverse a string using stack
# Function to create an empty stack.
# It initializes size of stack as 0
def createStack():
stack = []
return stack
def size(stack):
return len(stack)
def isEmpty(stack):
if size(stack) == 0:
return true
def pop(stack):
if isEmpty(stack):
return
return stack.pop()
def reverse(string):
n = len(string)
Output:
Reversed string is RAJU PALADUGU
16. Create a queue and perform various operations on it.
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A function to do inorder tree traversal
def printInorder(root):
if root:
# First recur on left child
printInorder(root.left)
Output:
Inorder traversal of binary tree is
42513
if root:
# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Function call
print("Preorder traversal of binary tree is")
printPreorder(root)
Output:
Preorder traversal of binary tree is
12453
c)# A Program to do postorder tree traversal
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
if root:
# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Function call
print("\nPostorder traversal of binary tree is")
printPostorder(root)
Output:
Postorder traversal of binary tree is
45231
18. Construct a binary search tree and perform search operation.
# Binary Search Tree operations in Python
# Create a node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Inorder traversal
def inorder(root):
if root is not None:
# Traverse left
inorder(root.left)
# Traverse root
print(str(root.key) + "->", end=' ')
# Traverse right
inorder(root.right)
# Insert a node
def insert(node, key):
return current
# Deleting a node
def deleteNode(root, key):
root.key = temp.key
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
print("\nDelete 10")
root = deleteNode(root, 10)
print("Inorder traversal: ", end=' ')
inorder(root)
Output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 10
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 14->
19.Implement Depth First Search, Breadth First Search traversals on a graph.
gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
dfs(gdict, 'a')
Output:
DFS Traversal --- a b d e c
def marked(n):
print(n)
Output:
BFS Traversal --- a b c d e
return min_index
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
Output:
Consider source node as “0”
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Python Example programs
1. Write a program to demonstrate different number datatypes in python.
Source code:
i=7 c=24+8j
f=701
s='HELLO EVERYONE!!\nThis is john\'s python programming..'
# NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)
b= True
print("the value of c is:",i,'\nits type is:',type(i))
print("the value of c is:",f,'\nits type is:',type(f))
print("the value of c is:",c,'\nits type is:',type(c))
print("the value of c is:",s,'\nits type is:',type(s))
rint("the value of c is:",b,'\nits type is:',type(b))
print('NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)')
Output:
2. Write a program to perform different arithmetic operations on numbers in python.
Source code:
a=10; b=3
print("addition of a:",a,"&b:",b,"is:",a+b)
print("substraction of a:",a,"&b:",b,"is:",a-b)
print("multiplication of a:",a,"&b:",b,"is:",a*b)
print("division of a:",a,"&b:",b,"is:",a/b)
print("moduli of a:",a,"&b:",b,"is:",a%b)
print("exponent of a:",a,"&b:",b,"is:",a**b)
Output:
3. Write a program to create, concatenate and print a string and accessing sub-string from
a given string.
Source code:
pi=3.14
s= "Venkata"
v= "Subhramanyam"
print("the value of s is:",s)
print("the value of v is:",v)
string_add = s+v
print("after concatenating s and v the string is:",s+v)
print("NOTE: variables after '+' operator must be converted to string before using them as strings\n
otherwise value will be considered as its class type")
print(text)
Output:
4. Write a python script to print the current date in following format
“SunMay 29 02:26:23 IST 2017”
Source code:
import time
import datetime
x =datetime.datetime.now()
print(x.strftime("%c"))
Output:
5. Write a python program to create, append and remove lists in python.
Source code:
print(colleges)
colleges.append("MVSR")
#checking if its added or not
print(colleges)
#adding a new college at a positon
colleges.insert(1,"BHARAT") print(colleges)
#remove a name from colleges
colleges.remove("BHARAT") print(colleges)
#remove a name with an index value
del colleges[1]
print(colleges)
Output:
6. Write a program to demonstrate working with tuples in python
Source code:
if "SIIET" in colleges:
Output:
7. Write a program to demonstrate working with dictionaries in python
Source code:
# creating a dictionary
for SIIET college = {
"name": "siiet",
"code": "INDI",
"id": "x3"
}
print(college)
#adding items to dictionary
college["location"] = "IBP"
print(college)
#changing values of a key
college["location"] = "sheriguda"
print(college)
# to remove items use
pop()
college.pop("code")
print(college)
#know the length using len() print("length
of college is:",len(college))#to copy the
same dictionary use copy() mycollege=
college.copy() print(mycollege)
Output:
8. Write a python program to find largest of three numbers
Source code:
# user-defined function to know which number is
larger def bigOf3(a,b,c):
if(a>b):
if(a>c):
print("a is greater than b and c")
else:
print("c is greater than a and b")
elif(b>c):
print("b is greater than a and c")
else:
print("c is greater than a and b")
txt= input("enter a,b,c values:") a,b,c=
txt.split()
bigOf3(int(a),int(b),int(c)) #calling the function
Output:
9. Write a python program to convert temperature to and from Celsius to fahrenheit.
Source code:
while(1):
print("1.CELSIUS TO FAHRENHEIT\n2.FAHRENHEIT TO CELSIUS\n3.EXIT\n")
choice=input("ENTER YOUR CHOICE:")
ch=int(choice)
if(ch==1):
c=int(input("ENTER TEMPERATURE IN CELSIUS:"))
f=((9*c)/5)+32
print("converted temperature is:",f)
elif(ch==2):
f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))
c=((f-32)/9)*5
print("converted temperature is:",c)
elif(ch==3):
exit()else:
print("wrong choice")
Output:
10. Write a python program to construct the following pattern using nested for
loop:
*
**
***
****
*****
*****
****
***
**
Source code:
n=int(input("ENTER A VALUE:"))
fo
r
x
i
n
r
a
n
g
e
(
0
,
n
+
1
,
1
)
:
p
r
i
n
t
(
x
*
'
*
'
)
if(x==n):
Output:
***********************
ALL
THE
BEST
***********************