AD3271 DSD Lab Manual
AD3271 DSD Lab Manual
To create a class Student and a function to print name, batch number and department of the
students using python.
Algorithm:
Step 1: Start
Step 4: Define a function stud(self) to print Name, Batch Number and Department.
Step 6: Stop.
Program:
class Student:
Name = 'Hari'
Batch_Number = '1001'
Department = 'AI&DS'
def stud(self):
print('Name is:',self.Name)
print('Batch_Number is:',self.Batch_Number)
print('Department is:',self.Department)
S1=Student()
S1.stud()
Output:
Result:
Thus the python program to create a class Student and a function to print name, batch
number and department of the students has been executed and verified.
Aim:
To create a class Employee and a function to print Name, Position and Company of
employees using python.
Algorithm:
Step 1: Start
Step 2: Create a class Employee.
Step 3: Assign values to variables Name, Position and Company.
Step 4: Define a function func(self) to print Name, Position and Company.
Step 5: Create an object s and call employee() function.
Step 6: Stop.
Program:
class Employee:
name="abc"
position="manager"
company="google"
def func(self):
print("name is",self.name)
print("position is",self.position)
print("company is",self.company)
s=employee()
s.func()
Output:
Result:
Thus the python program to create a class Employee and a function to Name, Position and
Company of Employee has been executed and verified.
Aim:
To create an abstract class Animal and it is inherited by class representing different animals
and defines abstract methods to display the kind of sound those animals produce.
Algorithm:
Step 1: Start
Step 3: Create a class Animal and to be inherited for Snake, Dog, Lion.
Step 6: Stop
Program:
class Animal(ABC):
def move(self):
pass
class Human(Animal):
def move(self):
class Snake(Animal):
def move(self):
class Dog(Animal):
def move(self):
class Lion(Animal):
def move(self):
R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
K = Lion()
K.move()
Output:
Result:
Thus the Python program to create an abstract class Animal and it is inherited by class
representing different animals and also defines abstract methods to display the kind of sound
those animals produce are executed successfully and verified.
Aim:
Algorithm:
Step 1: Start
Step 7: Stop
Program:
class Person:
self.name = name
self.age = age
def displayData(self):
print(self.name)
print(self.age)
class Employee(Person):
super().__init__(name, age)
self.empId = id
def displayData(self):
print(self.name)
print(self.age)
print(self.empId)
person.displayData()
emp.displayData()
Output:
Result:
Thus the Python program to implement the concept of Polymorphism through inheritance was
executed successfully and verified.
Aim:
To create a Python class program to deposit, withdraw, display the balance in account.
Algorithm:
Step 1: Start
Step 4: Create an object ‘s’ to use the functions deposit, withdraw and display.
Step 5: Stop
Program:
class Bank_Account:
def __init__(self):
self.balance=0
def deposit(self):
self.balance += amount
def withdraw(self):
if self.balance>=amount:
self.balance-=amount
else:
def display(self):
s = Bank_Account()
s.deposit()
s.withdraw()
s.display()
Output:
Result:
Thus the Python program to deposit, withdraw, display the balance in account has been executed
successfully and verified.
2. RECURSIVE ALGORITHMS
Aim:
Algorithm:
Step 1: Start
Step 6: Stop
Program:
class Test:
f=1
f=f*i
return f
n = int(input("Enter a number:"))
obj = Test()
f = obj.fact(n)
print("Factorial is:", f)
Output:
Result:
Thus the simple Python program to create recursive function to determine factorial of a given
number has been executed successfully and verified.
Aim:
Algorithm:
Step 1: Start
Step 2: Create fibonacci function. Declare variables like n1, n2, count.
Step 6: Use loop for the following steps. -> nth = n1 + n2 -> n1 = n2 -> n2 = nth and increase
value of count each time by 1.
Step 7 : End
Program:
class Fibo:
def __init__(self,name):
self.num = num
def fibonacci(self):
n1,n2 = 0,1
count = 0
if num <= 0:
elif num == 1:
print(n1)
else:
print("Fibonacci Sequence:")
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
fib = Fibo(num)
fib.fibonacci()
Output:
Result:
Thus the simple Python recursive function to determine Fibonacci series of a given number
has been executed successfully and verified.
Aim:
To create a simple Python recursive function to determine Greatest Common Divisor (GCD)
of a given number.
Algorithm:
Step 1: Start
Step 3: Next, use recursion to check if both the given numbers are divisible by any
number and without leaving any remainder.
Program:
class GCDs:
def __init__(self,a,b):
self.a = a
self.b = b
def GCD(self):
self.a,self.b = self.b,self.a
n=1
gcd = 0
gcd = n
n += 1
a = int(input("Enter a: "))
b = int(input("Enter b: "))
gcd = GCDs(a,b)
gcd.GCD()
Output:
Result:
Thus the simple Python recursive function to determine Greatest Common Divisor (GCD) of a
given number was executed successfully and verified.
Aim:
To create a user defined list and perform operations like appending, sorting and reversing by
choice based system using array concept.
Algorithm:
Step 1: Start
Step 2: Create class array
Step 3: Get an empty list L1 and number of elements in list ‘l’.
Step 4: for i in range 0 and ‘l’ goto step 5.
Step 5: Get an element to be in list and append to the empty list L1.
Step 6: Define a function appending and get an element to be appended.
Step 7: Define a function sorting and sort the list L1.
Step 8: Define a function reversing and reverse the list L1.
Step 9: Create an object a1.
Step 10: Print chioce1=appending, choice2=sorting and choice3=reversing.
Step 11: Stop
Program:
class arr:
l=int(input('Enter number of elements'))
L1=[]
for i in range(0,l):
s=int(input('Enter elements to be added'))
L1.append(s)
print('The given list is',L1)
def appending(self):
a=int(input('Enter element to be appended'))
self.L1.append(a)
print('List after appended')
print(self.L1)
def sorting(self):
self.L1.sort()
print('List after sorting')
print(self.L1)
def reversing(self):
self.L1.reverse()
print('List after reversing')
print(self.L1)
a1=arr()
print('choice 1=appending choice 2=sorting choice 3=reversing\n')
17 E SHAPNA RANI, AP/CSE
Saranathan College of Engineering
Output:
Result:
Thus the python program to implement operations like append, sort, reverse the list using arrays
has been executed and verified.
Aim:
To implement List by performing operations like append, display using Linked list.
Algorithm:
Step 1: Start
Step 2: Create a class Node with instance variables data and next.
Step 3: Create a class LinkedList with instance variables head and last_node.
Step 4: The variable head points to the first element in the linked list while last_node points
to the last.
Step 5: Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
Step 6: Create an instance of LinkedList, append data to it and display the list.
Step 7: Stop
Program:
class Node:
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
current = current.next
a_llist = LinkedList()
for i in range(n):
a_llist.append(data)
a_llist.display()
Output:
Result:
Thus the python program to implement the operations in list using linked list was successfully
executed and verified.
Aim:
To create a python program for implementing the concept of Stack using arrays.
Algorithm:
Step 1: Start
Step 2: Create a class StackUsingArray with instance variable items initialized to an empty
list.
Step 3: Define methods push, pop and is_empty inside the class StackUsingArray.
Step 4: The method push appends data to items.
Step 5: The method pop removes the first element in items.
Step 6: The method is_empty returns True only if items is empty.
Step 7: The methos printStack() prints the data element of the stack.
Step 8: Create an instance of Stack and present a menu to the user to perform operations on
the stack.
Step 9: Stop
Program:
class StackUsingArray:
def __init__(self):
self.stack = []
self.stack.append(element)
def pop(self):
if(not self.isEmpty()):
lastElement = self.stack[-1]
del(self.stack[-1])
return lastElement
else:
def isEmpty(self):
return self.stack == []
def printStack(self):
print(self.stack)
if __name__ == "__main__":
s = StackUsingArray()
while(True):
if(el == 1):
s.push(item)
if(el == 2):
print(s.pop())
if(el == 3):
print(s.isEmpty())
if(el == 4):
s.printStack()
if(el == 5):
break
Output:
10
20
30
30
20
10
True
[]
Result:
Thus the python program to create the concept of Stack using array was implemented
successfully and verified.
Aim:
To create a Python classes program to implement a stack using a linked list.
Algorithm:
Step 1: Start
Step 2: Create a class Node with instance variables data and next.
Step 3: Create a class Stack with instance variable head.
Step 4: The variable head points to the first element in the linked list.
Step 5: Define methods push and pop inside the class Stack.
Step 6: The method push adds a node at the front of the linked list.
Step 7: The method pop returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.
Step 8: Create an instance of Stack and present a menu to the user to perform operations on
the stack.
Step 9: Stop
Program:
class Node:
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped
a_stack = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
operation = do[0].strip().lower()
if operation == 'push':
a_stack.push(int(do[1]))
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
break
Output:
push <value>
pop
quit
push <value>
pop
quit
push <value>
pop
Popped value: 20
push <value>
pop
quit
Popped value: 10
push <value>
pop
quit
Stack is empty.
push <value>
pop
quit
Result:
Thus the Python classes program to implement a stack using a linked list was implemented
successfully and verified.
Aim:
To create a queue and allows the user to perform enqueue and dequeue operations on it in
python classes.
Algorithm:
Step 1: Start
Step 2: Create a class Queue with instance variable items initialized to an empty list.
Step 3: Define methods enqueue, dequeue and is_empty inside the class Queue.
Step 4: The method enqueue appends data to items.
Step 5: The method dequeue dequeues the first element in items.
Step 6: The method is_empty returns True only if items is empty.
Step 7: Create an instance of Queue and present a menu to the user to perform operations on
the queue.
Step 8: Stop
Program:
class Queue:
def __init__(self):
self.queue = []
self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def display(self):
print(self.queue)
def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.display()
q.dequeue()
q.display()
Output:
Result:
Thus the Queue that allows the user to perform enqueue and dequeue operations on it in
python classes has been executed successfully and verified.
Aim:
To create a python program for implementing the concept of Queue using Linked list.
Algorithm:
Step1: Start
Step 2: Create a class Node with instance variables data and next.
Step 3: Create a class Queue with instance variables head and last.
Step 4: The variable head points to the first element in the linked list while last points to the
last element.
Step 5: Define methods enqueue and dequeue inside the class Queue.
Step 6: The method enqueue adds a node at the end of the linked list.
Step 7: The method dequeue returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.
Step 8: Create an instance of Queue and present a menu to the user to perform operations on
the queue.
Step 9: Stop
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
def enqueue(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
return to_return
a_queue = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
dequeued = a_queue.dequeue()
if dequeued is None:
print('Queue is empty.')
else:
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
Output:
enqueue <value>
dequeue
quit
enqueue <value>
dequeue
quit
enqueue <value>
dequeue
quit
enqueue <value>
dequeue
quit
Dequeued element: 10
enqueue <value>
dequeue
quit
Result:
Thus the python program to implement the concept of Queue using Linked list has been
executed successfully and verified.
Aim:
To create a Python class program for converting an Infix expression to Prefix expression
using Stack.
Algorithm:
Step 4: Now reverse each bracket. If you encountered any open bracket ‘(‘, reverse it and
make it close bracket ‘)’ and vice versa
Step 5: Convert the reverse string into the postfix expression and if during conversion you
find any operator then, we have to check its precedence with the one in stack.
Step 6: If precedence of current operator is higher than the one in stack then push the current
operator into the stack else pop the operator from the stack.
Program:
class infix_to_prefix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
return self.size==-1
def seek(self):
if self.isempty():
return False
else:
return self.items[self.size]
def isoperand(self,i):
def reverse(self,expr):
rev=""
for i in expr:
if i is '(':
i=')'
elif i is ')':
i='('
rev=i+rev
return rev
def infixtoprefix(self,expr):
prefix=''
for i in expr:
if len(expr)%2==0:
return False
elif self.isoperand(i):
prefix+=i
elif i in '+-*/^':
prefix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
prefix+=o
o=self.pop()
print(prefix)
while len(self.items):
if self.seek()=='(':
self.pop()
else:
prefix+=self.pop()
print(prefix)
return prefix
s=infix_to_prefix()
rev=""
rev=s.reverse(expr)
result=s.infixtoprefix(rev)
if result!=False:
prefix=s.reverse(result)
Output:
Result:
Thus the Python class program to convert an Infix expression to prefix expression using
Stack has been executed and verified successfully.
Aim:
To write a Python class program to implement execution of CPU First in First out Scheduling
using Queue.
Algorithm:
Step 1: Start
Step 2: Input the processes along with their Burst time (bt) and Arrival time (at)
Step 4: As first process that comes need not to wait so waiting time for process 1 will be 0
i.e. wt[0] = 0
no_of_processes.
Step 9: Stop
Program:
d = dict()
for i in range(n):
key = "P"+str(i+1)
l = []
l.append(a)
l.append(b)
d[key] = l
ET = []
for i in range(len(d)):
# first process
if(i==0):
ET.append(d[i][1][1])
else:
ET.append(ET[i-1] + d[i][1][1])
TAT = []
for i in range(len(d)):
TAT.append(ET[i] - d[i][1][0])
WT = []
for i in range(len(d)):
WT.append(TAT[i] - d[i][1][1])
avg_WT = 0
for i in WT:
avg_WT +=i
avg_WT = (avg_WT/n)
for i in range(n):
Output:
Result:
Thus the Python class program to implement execution of CPU First in First out Scheduling
using Queue has been executed and verified successfully.
Aim:
To write a Python classes and objects to implement the concept of Bubble sort.
Algorithm:
Step 1: Start
Step 2: Get the total number of elements and the input data from the user.
Step 3: Starts from the first index: ‘a’ and compares the first and second element: a[j] and a[j+1]
Step 6: The above process continues until the last element a[n-1]
Step 7: Stop
Program:
class BubbleSort:
def __init__(self):
self.a=[]
def inp(self):
n=int(input("Enter number of items: "))
for i in range(1,n+1):
m=int(input("Enter the %d element: "%i))
self.a.append(m)
print("Your List:",self.a)
return self.a
def bub(self,a):
l=len(self.a)
a=self.a
for i in range(l-1):
for j in range(l-1-i):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print("Sorted List:",a)
b=BubbleSort()
c=b.inp()
b.bub(c)
Output:
Result:
Thus the above Python program for implementing the concept of Bubble sort has been
executed and verified successfully.
Aim:
To write a Python classes and objects to implement the concept of Insertion sort.
Algorithm:
Step 1: Start
Step 2: If the element is the first one, it is already sorted.
Step 3: Move to next element
Step 4: Compare the current element with all elements in the sorted array
Step 5: If the element in the sorted array is smaller than the current element, iterate to the
next element. Otherwise, shift the entire greater element in the array by one position towards
the right
Step 6: Insert the value at the correct position
Step 7: Repeat until the complete list is sorted
Step 8: Stop
Program:
class InsertionSort:
def __init__(self):
self.a=[]
def inp(self):
for i in range(1,n+1):
self.a.append(m)
print("Your List:",self.a)
return self.a
def ins(self,a):
l=self.a
for i in range(0,len(l)-1):
smallest=i
for j in range(i+1,len(l)):
if l[j]<l[smallest]:
smallest=j
l[i],l[smallest]=l[smallest],l[i]
print("Sorted List:",l)
i=InsertionSort()
c=i.inp()
i.ins(c)
Output:
Result:
Thus the above Python program for implementing the concept of Insertion sort has been
executed and verified successfully.
Aim:
To write a Python classes and objects to implement the concept of Quick sort.
Algorithm:
Step 2: Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 3: Define two variables i and j. Set i and j to first and last elements of the list
respectively.
Program:
class QuickSort:
def __init__(self):
self.a=[]
def inp(self):
for i in range(1,n+1):
self.a.append(m)
print("Your List:",self.a)
return self.a
def quick(self,a):
l=self.a
key=l[step]
j=step-1
l[j+1],j=l[j],j-1
l[j+1]=key
print("Sorted List:",l)
q=QuickSort()
c=q.inp()
q.quick(c)
Output:
Result:
Thus the above Python program for implementing the concept of Quick sort has been executed
and verified successfully.
Aim:
Algorithm:
Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the
array.
Step 3: If both are matched, display "Target element is found" and terminate the
Linear Search function.
Step 4: If both are not matched, compare the search element with the next element in
the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared
with the last element of the array.
Step 6 - If the last element in the list does not match, the Linear Search Function will
be terminated, and the message "Element is not found" will be displayed.
Program:
class Linear_search:
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
def input(self):
alist = alist.split()
return alist,key
def srh(self,key,index):
if index < 0:
else:
ls=Linear_search()
l,k=ls.input()
i=ls.linear_search(l,k)
out=ls.srh(k,i)
Output:
Result:
Thus the Python class program to implement the concept of linear search has been executed
successfully and verified.
Aim:
Algorithm:
Program:
class Binary_search:
start = 0
end = len(alist)
end = mid
start = mid + 1
else:
return mid
return -1
def input(self):
alist = alist.split()
def srh(self,key,index):
if index < 0:
else:
bs=Binary_search()
l,k=bs.input()
i=bs.binary_search(l,k)
out=bs.srh(k,i)
Output:
Result:
Thus the Python class program to implement the concept of binary search has been executed
successfully and verified.
Aim:
Algorithm:
Step1: Start
Step 2: Get the Table size as a user input
Step 3: Create hash function
Step 4: To insert a node into the hash table, need to find the hash index for the given key
and it could be calculated using the hash function.
Step 5: Display hash entry for each element.
Step 6: Stop
Program:
class hashTable:
def __init__(self):
self.size=int(input("Enter the size of the hash table:"))
self.table=list(0 for i in range(self.size))
self.elementCount=0
self.comparisons=0
def isFull(self):
if self.elementCount==self.size:
return True
else:
return False
def hashFunction(self,element):
return element%self.size
def insert(self,element):
if self.isFull():
return False
isStored=False
position=self.hashFunction(element)
if self.table[position]==0:
self.table[position]=element
print("Element "+str(element)+" at position "+str(position))
isStored=True
self.elementCount+=1
else:
print("\tCollision has occured for element "+str(element)+" at
position"+str(position)+" finding new Position")
while self.table[position]!=0:
position+=1
if position>=self.size:
position=0
self.table[position]=element
isStored=True
self.elementCount+=1
return isStored
def search(self,element):
found=False
position=self.hashFunction(element)
self.comparisons+=1
if (self.table[position]==element):
return position
isFound=True
else:
temp=position-1
while position<self.size:
if self.table[position]!=element:
position+=1
self.comparisons+=1
else:
return position
position=temp
while position>=0:
if self.table[position]!=element:
position-=1
self.comparisons+=1
else:
return position
if not found:
print("Element not found")
return False
def remove(self,element):
position=self.search(element)
if position is not False:
self.table[position]=0
print("Element "+str(element)+" is deleted")
self.elementCount-=1
else:
print("Element "+str(element)+" is deleted")
return
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + "=" + str(self.table[i]))
print("The number of elements in the Table are: "+str(self.elementCount))
table1=hashTable()
table1.insert(12)
table1.insert(26)
table1.insert(31)
table1.insert(17)
table1.insert(90)
table1.insert(28)
table1.insert(88)
table1.insert(40)
table1.insert(77)
table1.display()
print("The position of element 31 is:"+str(table1.search(31)))
print("The position of element 28 is:"+str(table1.search(28)))
print("The position of element 90 is:"+str(table1.search(90)))
print("The position of element 77 is:"+str(table1.search(77)))
print("The position of element 1 is:"+str(table1.search(1)))
print("\nTotal number of comparisons done ofr searching="+str(table1.comparisons))
print()
table1.remove(90)
table1.remove(12)
table1.display()
Output:
Result:
Thus the python class program to implement the concept of hashing has been executed and
verified successfully.
Aim:
To write a Python class program to implement the representation and Traversal algorithm of
a tree.
Algorithm:
Step 1: The left sub tree of a node contains smaller nodes than a root node.
Step 2: The right sub tree of a node contains greater nodes than a root node.
Step 3: Both the left and right sub trees must also be binary search trees.
Step 4: There are three types of tree traversals: Preorder, Postorder, and Inorder.
Pre-order traversal
Algorithm:
1. Visit the root (we will print it when we visit to show the order of visiting)
2. Traverse the left sub tree in pre-order
3. Traverse the right sub tree in pre-order
In-order traversal
Visit the root node in between the left and right node (in)
Algorithm:
1. Traverse the left sub tree in in-order
2. Visit the root (we will print it when we visit to show the order of visiting)
3. Traverse the right sub tree in in-order
Post-order traversal
Visit the root node after (post) visiting the left and right sub tree.
Algorithm:
1. Traverse the left sub tree in in-order
2. Traverse the right sub tree in in-order
3. Visit the root (we will print it when we visit to show the order of visiting)
Program:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val),
def printPreorder(root):
if root:
print(root.val),
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Preorder traversal of binary tree is")
printPreorder(root)
print ("\nInorder traversal of binary tree is")
printInorder(root)
print ("\nPostorder traversal of binary tree is")
printPostorder(root)
Output:
Result:
Thus the python program to implement the concept of tree representation and traversal
algorithm has been implemented successfully.
Aim:
To write a Python class program to create a Binary Search Tree and to perform insertion,
deletion and inorder traversal operations.
Algorithm:
Step 1: Start the Process
Step 2: Create a class Node with instance variables key, left, right and parent.
Step 3: Define methods insert, inorder, minValueNode, deleteNode Node.
Step 4: The method insert takes a node as argument and inserts that node in the BST with the
BSTNode object as root.
Step 5: The method inorder displays the inorder traversal of the BST with the Node object as
root.
Step 6: The method minValueNode finds the left-most node in the BST with the Node object
as root.
Step 7: The method deleteNode removes the current BSTNode object from the BST.
Step 8: Stop the Process
Program:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(str(root.key) + "->", end=' ')
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current
def deleteNode(root, key):
if root is None:
return root
Output:
Result:
Thus the Python class program to implement the concept of Binary Search Tree has been
executed and verified successfully.
Aim:
To write a Python class program to create a binary max-heap and presents a menu to the user
to perform various operations on it.
Algorithm:
Step 1: Start
Step 2: Create a class BinaryHeap with an instance variable items set to an empty list. This
empty list is used to store the binary heap.
Step 3: Define methods size, parent, left, right, get, get_max, extract_max, max_heapify,
swap and insert.
Step 4: The method size returns the number of elements in the heap.
Step 5: The method parent takes an index as argument and returns the index of the parent.
Step 6: The method left takes an index as argument and returns the index of its left child.
Step 7: The method right takes an index as argument and returns the index of its right child.
Step 8: The method get takes an index as argument and returns the key at the index.
Step 9: The method get_max returns the maximum element in the heap by returning the first
element in the list items.
Step 10: The method extract_max returns the the maximum element in the heap and removes
it.
Step 11: The method max_heapify takes an index as argument and modifies the heap
structure at and below the node at this index to make it satisfy the heap property.
Step 12: The method swap takes two indexes as arguments and swaps the corresponding
elements in the heap.
Step 13: The method insert takes a key as argument and adds that key to the heap.
Step 14: Stop
Program:
class BinaryHeap:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def parent(self, i):
return (i - 1)//2
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def get(self, i):
return self.items[i]
def get_max(self):
if self.size() == 0:
return None
return self.items[0]
def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)
def swap(self, i, j):
self.items[i], self.items[j] = self.items[j], self.items[i]
def insert(self, key):
index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p
bheap = BinaryHeap()
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(bheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation == 'quit':
break
Output:
Result:
Thus the Python class program to create a binary max-heap and presents a menu to the user
to perform various operations on it has been executed and verified successfully.
Aim:
To write a Python OOP program to implement the concept of Breadth First Search.
Algorithm:
Step 1: Start
Step 2: Take the graph as input and find the adjacency list
Step 3: Take the input Source and Destination from the user
Step 3: Start at a random vertex and visit all nodes using Breadth First Search (BFS)
Step 4: Use Queue for BFS.
Step 5: Stop
Program:
class BFS(Graph):
def __init__(self, nodes, edges, is_directed=False):
super().__init__(nodes, is_directed)
self.add_multiple_edges(edges)
self.visited = {}
self.level = {}
self.parent = {}
self.output = []
self.queue = Queue()
Output:
Result:
Thus the Python OOP program to implement the concept of Breadth First Search
using Queue has been executed and verified successfully.
Aim:
To write a Python OOP program to implement the concept of Depth First Search.
Algorithm:
Step 1: Start
Step 2: Take the graph as input and find the adjacency list
Step 3: Take the input Source and Destination from the user
Step 3: Start at a random vertex and visit all nodes using Depth First Search (BFS)
Step 4: Use Stack for DFS.
Step 5: Stop
Program:
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, key):
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
return self.key
def add_neighbour(self, dest, weight):
self.points_to[dest] = weight
def get_neighbours(self):
return self.points_to.keys()
def get_weight(self, dest):
return self.points_to[dest]
def does_it_point_to(self, dest):
def display_dfs(v):
display_dfs_helper(v, set())
def display_dfs_helper(v, visited):
visited.add(v)
print(v.get_key(), end=' ')
for dest in v.get_neighbours():
if dest not in visited:
display_dfs_helper(dest, visited)
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('dfs <vertex key>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'dfs':
key = int(do[1])
print('Depth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_dfs(vertex)
print()
Output:
Result:
Thus the Python OOP program to implement the concept of Depth First Search has been
executed and verified successfully.
72 E SHAPNA RANI, AP/CSE
Saranathan College of Engineering
DIJISKTRA ALGORITHM
Aim:
To write a Python OOP program to implement the concept of single Source shortest path
using dijisktra algorithm.
Algorithm:
Step 1: Start the process
Step 2: Create classes for Graph and Vertex.
Step 3: Create a function dijkstra that takes a Graph object and a source vertex as arguments.
Step 4: The function begins by creating a set unvisited and adding all the vertices in the
graph to it.
Step 5: A dictionary distance is created with keys as the vertices in the graph and their value
all set to infinity.
Step 6: distance [source] is set to 0.
Step 7: The algorithm proceeds by finding the vertex that has the minimum distance in the set
unvisited.
Step 8: It then removes this vertex from the set unvisited.
Step 9: Then all the neighbors of this vertex that have not been visited yet have their
distances updated.
Step 10: The above steps repeat until the set unvisited becomes empty.
Step 11: The dictionary distance is returned.
Step 12: This algorithm works for both undirected and directed graphs.
Step 13: Stop the process
Program:
class Graph:
def __init__(self):
self.vertices = {}
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
return self.key
def get_neighbours(self):
return self.points_to.keys()
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('shortest <source vertex key>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:
print('Edge already exists.')
print('Edges: ')
for v in g:
Output:
Result:
Thus the Python OOP program to implement the concept of single Source shortest
path using dijisktra algorithm has been executed and verified successfully.
PRIM’S ALGORITHM
Aim:
To write a Python OOP program to implement the concept of Minimum Spanning Tree using
Prim’s algorithm.
Algorithm:
Program:
class Graph:
def __init__(self):
self.vertices = {}
def display(self):
print('Vertices: ', end='')
for v in self:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in self:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
return self.key
def get_neighbours(self):
return self.points_to.keys()
def mst_prim(g):
mst = Graph()
if not g:
return mst
nearest_neighbour = {}
smallest_distance = {}
unvisited = set(g)
u = next(iter(g))
mst.add_vertex(u.get_key())
unvisited.remove(u)
for n in u.get_neighbours():
if n is u:
continue
nearest_neighbour[n] = mst.get_vertex(u.get_key())
smallest_distance[n] = u.get_weight(n)
while (smallest_distance):
outside_mst = min(smallest_distance, key=smallest_distance.get)
inside_mst = nearest_neighbour[outside_mst]
mst.add_vertex(outside_mst.get_key())
mst.add_edge(outside_mst.get_key(), inside_mst.get_key(),
smallest_distance[outside_mst])
mst.add_edge(inside_mst.get_key(), outside_mst.get_key(),
smallest_distance[outside_mst])
unvisited.remove(outside_mst)
del smallest_distance[outside_mst]
del nearest_neighbour[outside_mst]
for n in outside_mst.get_neighbours():
if n in unvisited:
if n not in smallest_distance:
smallest_distance[n] = outside_mst.get_weight(n)
nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())
else:
if smallest_distance[n] > outside_mst.get_weight(n):
smallest_distance[n] = outside_mst.get_weight(n)
nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())
return mst
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('mst')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:
print('Edge already exists.')
elif operation == 'mst':
mst = mst_prim(g)
print('Minimum Spanning Tree:')
mst.display()
print()
Output:
Result:
Thus the Python OOP program to implement the concept of Minimum Spanning Tree using
Prim’s algorithm has been executed and verified successfully.