0% found this document useful (0 votes)
18 views

AD3271 DSD Lab Manual

Uploaded by

Gomathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

AD3271 DSD Lab Manual

Uploaded by

Gomathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Saranathan College of Engineering

1. SIMPLE ADTs AS PYTHON CLASSES

1a. PYTHON PROGRAM TO CREATE CLASS STUDENT


Aim:

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 2: Create a class Student.

Step 3: Assign values to variables Name, Batch number and Department.

Step 4: Define a function stud(self) to print Name, Batch Number and Department.

Step 5: Create an object S1 and call stud() function.

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()

1 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

2 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

1b. CREATE A CLASS EMPLOYEE

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()

3 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

4 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

1c. ABSTRACT CLASS AND INHERITANCE

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 2: Import abstract method ABC and abstract methods.

Step 3: Create a class Animal and to be inherited for Snake, Dog, Lion.

Step 4: Define the functions and create an object for classes.

Step 5: Call the driver code

Step 6: Stop

Program:

from abc import ABC, abstractmethod

class Animal(ABC):

def move(self):

pass

class Human(Animal):

def move(self):

print("I can walk and run")

class Snake(Animal):

def move(self):

print("I can crawl")

class Dog(Animal):

def move(self):

print("I can bark")

class Lion(Animal):

5 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

def move(self):

print("I can roar")

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.

6 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

1d. POLYMORPHISM THROUGH INHERITANCE

Aim:

To create a Python program to implement the concept of Polymorphism through inheritance.

Algorithm:

Step 1: Start

Step 2: Create a class Person.

Step 3: Initialize the variables ‘name’ and ‘age’.

Step 4: Create another class Employee to be inherited from class Person.

Step 5: Call the constructor of super class in class Employee.

Step 6: Display the data

Step 7: Stop

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):

super().__init__(name, age)

self.empId = id

def displayData(self):

print('In child class displayData method')

7 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

print(self.name)

print(self.age)

print(self.empId)

person = Person('Karthik Shaurya', 26)

person.displayData()

emp = Employee('Karthik Shaurya', 26, 'E317')

emp.displayData()

Output:

Result:

Thus the Python program to implement the concept of Polymorphism through inheritance was
executed successfully and verified.

8 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

1e. PYTHON CLASS PROGRAM TO BANK_ACCOUNT

Aim:
To create a Python class program to deposit, withdraw, display the balance in account.

Algorithm:

Step 1: Start

Step 2: Create a class Bank_Account having deposit and withdraw methods.

Step 3: Write functions to credit and debit the amount in account.

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

print("Hello!!! Welcome to the Deposit & Withdrawal Machine")

def deposit(self):

amount=float(input("Enter amount to be Deposited: "))

self.balance += amount

print("\n Amount Deposited:",amount)

def withdraw(self):

amount = float(input("Enter amount to be Withdrawn: "))

if self.balance>=amount:

self.balance-=amount

print("\n You Withdrew:", amount)

else:

print("\n Insufficient balance ")

def display(self):

9 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

print("\n Net Available Balance=",self.balance)

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.

10 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

2. RECURSIVE ALGORITHMS

2a. FACTORIAL OF A GIVEN NUMBER

Aim:

To create a simple Python recursive function to determine factorial of a given number.

Algorithm:

Step 1: Start

Step 2: Create a class Test and initialize the value f = 1.

Step 3: Create an object for the class Test.

Step 4: The function fact() is called by using the object obj.

Step 5: Compute the factorial multiplication by f = f * i and return f

Step 6: Stop

Program:

class Test:

def fact(self, n):

f=1

for i in range(1, n + 1):

f=f*i

return f

n = int(input("Enter a number:"))

obj = Test()

f = obj.fact(n)

print("Factorial is:", f)

11 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:

Thus the simple Python program to create recursive function to determine factorial of a given
number has been executed successfully and verified.

12 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

2b. FIBONACCI SERIES OF NUMBERS

Aim:

To create a simple Python recursive function to determine Fibonacci series of a given


number.

Algorithm:

Step 1: Start

Step 2: Create fibonacci function. Declare variables like n1, n2, count.

Step 3: Initialize the variables n1=0, n2=1, count =0.

Step 4: Enter the number of variables to be printed.

Step 5: Print first two numbers of series.

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:

print("Please Enter a positive integer")

elif num == 1:

print("Fibonacci sequence upto",num)

print(n1)

13 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

else:

print("Fibonacci Sequence:")

while count < num:

print(n1)

nth = n1 + n2

n1 = n2

n2 = nth

count += 1

num = int(input("Enter number:"))

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.

14 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

2c. GCD OF GIVEN NUMBERS

Aim:

To create a simple Python recursive function to determine Greatest Common Divisor (GCD)
of a given number.

Algorithm:

Step 1: Start

Step 2: Get 2 integer inputs from the user

Step 3: Next, use recursion to check if both the given numbers are divisible by any
number and without leaving any remainder.

Step 4:If true, then GCD = i

Step 5:Print the GCD of the two numbers

Step 6:End of the program

Program:

class GCDs:

def __init__(self,a,b):

self.a = a

self.b = b

def GCD(self):

if self.a > self.b:

self.a,self.b = self.b,self.a

n=1

gcd = 0

while n <= self.a:

if self.a % n == 0 and self.b % n == 0:

15 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

gcd = n

n += 1

print("GCD of the given two numbers is", gcd)

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.

16 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

3. IMPLEMENTATION OF LIST USING PYTHON ARRAYS

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

choice=int(input('Enter the choice:'))


if choice==1:
a1.appending()
elif choice==2:
a1.sorting()
else:
a1.reversing()

Output:

Enter number of elements: 5

Enter elements to be added: 10

The given list is [10]

Enter elements to be added: 20

The given list is [10, 20]

Enter elements to be added: 30

The given list is [10, 20, 30]

Enter elements to be added: 40

The given list is [10, 20, 30, 40]

Enter elements to be added: 50

The given list is [10, 20, 30, 40, 50]

choice 1=appending choice 2=sorting choice 3=reversing

Enter the choice: 1

Enter element to be appended: 60

List after appended:

[10, 20, 30, 40, 50, 60]

Enter the choice: 2

List after sorting:

18 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

[10, 20, 30, 40, 50]

Enter the choice: 3

List after reversing:

[50, 40, 30, 20, 10]

Result:

Thus the python program to implement operations like append, sort, reverse the list using arrays
has been executed and verified.

19 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

4. LINKED LIST IMPLEMENTATION OF LIST

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:

def __init__(self, data):

self.data = data

self.next = None

class LinkedList:

def __init__(self):

self.head = None

self.last_node = None

def append(self, data):

if self.last_node is None:

self.head = Node(data)

self.last_node = self.head

else:

self.last_node.next = Node(data)

20 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

self.last_node = self.last_node.next

def display(self):

current = self.head

while current is not None:

print(current.data, end = ' ')

current = current.next

a_llist = LinkedList()

n = int(input('How many elements would you like to add? '))

for i in range(n):

data = int(input('Enter data item: '))

a_llist.append(data)

print('The linked list: ', end = '')

a_llist.display()

Output:

Result:

Thus the python program to implement the operations in list using linked list was successfully
executed and verified.

21 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

5. IMPLEMENTATION OF STACK AND QUEUE ADTS

5a. IMPLEMENTATION OF STACK ADT USING ARRAYS

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 = []

def push(self, element):

self.stack.append(element)

def pop(self):

if(not self.isEmpty()):

lastElement = self.stack[-1]

del(self.stack[-1])

return lastElement

else:

return("Stack Already Empty")

22 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

def isEmpty(self):

return self.stack == []

def printStack(self):

print(self.stack)

if __name__ == "__main__":

s = StackUsingArray()

print("*"*5+" Stack Using Array "+5*"*")

while(True):

el = int(input("1 For Push\n2 For Pop\n3 To check if it is Empty\n4 To print Stack\n5 To


exit\n"))

if(el == 1):

item = input("Enter Element to push in stack:\n")

s.push(item)

if(el == 2):

print(s.pop())

if(el == 3):

print(s.isEmpty())

if(el == 4):

s.printStack()

if(el == 5):

break

23 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

***** Stack Using Array *****

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

Enter Element to push in stack:

10

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

Enter Element to push in stack:

20

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

Enter Element to push in stack:

30

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

['10', '20', '30']

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

30

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

20

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

24 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

10

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

True

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

[]

1 For Push 2 For Pop 3 To check if it is Empty 4 To print Stack 5 To exit

Result:

Thus the python program to create the concept of Stack using array was implemented
successfully and verified.

25 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

5b. IMPLEMENTATION OF STACK ADT USING LINKED LIST

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:

def __init__(self, data):

self.data = data

self.next = None

class Stack:

def __init__(self):

self.head = None

def push(self, data):

if self.head is None:

self.head = Node(data)

else:

new_node = Node(data)

new_node.next = self.head

26 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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')

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'push':

a_stack.push(int(do[1]))

elif operation == 'pop':

popped = a_stack.pop()

if popped is None:

print('Stack is empty.')

else:

print('Popped value: ', int(popped))

elif operation == 'quit':

break

27 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

push <value>

pop

quit

What would you like to do? push 10

push <value>

pop

quit

What would you like to do? push 20

push <value>

pop

What would you like to do? pop

Popped value: 20

push <value>

pop

quit

What would you like to do? pop

Popped value: 10

push <value>

pop

quit

What would you like to do? pop

Stack is empty.

push <value>

pop

28 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

quit

What would you like to do?

Result:

Thus the Python classes program to implement a stack using a linked list was implemented
successfully and verified.

29 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

5c. IMPLEMENTATION OF QUEUE ADT USING ARRAYS

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 = []

def enqueue(self, item):

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)

30 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

q = Queue()

q.enqueue(1)

q.enqueue(2)

q.enqueue(3)

q.enqueue(4)

q.enqueue(5)

q.display()

q.dequeue()

print("After removing an element")

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.

31 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

5d. IMPLEMENTATION OF QUEUE ADT USING LINKED LIST

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:

32 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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

33 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:
enqueue <value>

dequeue

quit

What would you like to do? enqueue 10

enqueue <value>

dequeue

quit

What would you like to do? enqueue 20

enqueue <value>

dequeue

quit

What would you like to do? enqueue 30

enqueue <value>

dequeue

quit

What would you like to do? dequeue

Dequeued element: 10

enqueue <value>

dequeue

quit

What would you like to do?

Result:

Thus the python program to implement the concept of Queue using Linked list has been
executed successfully and verified.

34 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

6. APPICATION OF STACK AND QUEUE

6a. APPLICATION OF STACK

CONVERSION OF INFIX TO PREFIX EXPRESSION

Aim:

To create a Python class program for converting an Infix expression to Prefix expression
using Stack.

Algorithm:

Step 1: Start the program

Step 2: Accept infix expression string as a input.

Step 3: Reverse the infix expression string

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.

Step 7: Finally reverse the postfix expression.

Step 8: Stop the process

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)

35 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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):

return (i.isalpha() or i in '1234567890')

def reverse(self,expr):

rev=""

for i in expr:

if i is '(':

i=')'

elif i is ')':

i='('

rev=i+rev

return rev

36 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

def infixtoprefix(self,expr):

prefix=''

print("Prefix expression after every iteration is:")

for i in expr:

if len(expr)%2==0:

print("Incorrect infix expr")

return False

elif self.isoperand(i):

prefix+=i

elif i in '+-*/^':

while (len(self.items) and self.precedence[i]<self.precedence[self.seek()]):

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:

37 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

prefix+=self.pop()

print(prefix)

return prefix

s=infix_to_prefix()

expr=input("Enter the expression:")

rev=""

rev=s.reverse(expr)

result=s.infixtoprefix(rev)

if result!=False:

prefix=s.reverse(result)

print(f"The prefix expr of {expr} is {prefix}")

Output:

38 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Result:

Thus the Python class program to convert an Infix expression to prefix expression using
Stack has been executed and verified successfully.

39 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

6b. APPLICATION OF QUEUE

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 3: Find Waiting time (wt) for all processes

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

Step 5: Find wt for all other processes i.e. for

wt[i] = bt[i-1] + wt[i-1] .

Step 6: Find Turnaround Time = Waiting_time + Burst_time for all processes.

Step 7: Find Average waiting time = Total_waiting_time / no_of_processes.

Step 8: Similarly, find average turnaround time = total_turn_around_time /

no_of_processes.

Step 9: Stop

Program:

print("FIRST COME FIRST SERVE SCHEDULLING")

n= int(input("Enter number of processes : "))

d = dict()

for i in range(n):

key = "P"+str(i+1)

a = int(input("Enter arrival time of process"+str(i+1)+": "))

40 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

b = int(input("Enter burst time of process"+str(i+1)+": "))

l = []

l.append(a)

l.append(b)

d[key] = l

d = sorted(d.items(), key=lambda item: item[1][0])

ET = []

for i in range(len(d)):

# first process

if(i==0):

ET.append(d[i][1][1])

# get prevET + newBT

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)

print("Process | Arrival | Burst | Exit | Turn Around | Wait |")

41 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

for i in range(n):

print(" ",d[i][0]," | ",d[i][1][0]," | ",d[i][1][1]," | ",ET[i]," | ",TAT[i]," |


",WT[i]," | ")

print("Average Waiting Time", avg_WT)

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.

42 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

7. IMPLEMENTATION OF SORTING ALGORITHMS

7a. IMPLEMENTATION OF BUBBLE SORT

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 4: If a[j] is greater than a[j+1], they are swapped

Step 5: Similarly, if a[j+1] is greater than a[j+2], they are swapped

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()

43 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

b.bub(c)

Output:

Result:

Thus the above Python program for implementing the concept of Bubble sort has been
executed and verified successfully.

44 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

7b. IMPLEMENTATION OF INSERTION SORT

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):

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 ins(self,a):

l=self.a

for i in range(0,len(l)-1):

smallest=i

45 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

46 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

7c. IMPLEMENTATION OF QUICK SORT

Aim:

To write a Python classes and objects to implement the concept of Quick sort.

Algorithm:

Step 1: Start the process

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.

Step 4: Increment i until list[i] > pivot then stop.

Step 5: Decrement j until list[j] < pivot then stop.

Step 6: If i < j then exchange list[i] and list[j].

Step 7: Repeat steps 3,4 & 5 until i > j.

Step 8: Exchange the pivot element with list[j] element.

Step 9: Stop the process

Program:

class QuickSort:

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)

47 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

return self.a

def quick(self,a):

l=self.a

for step in range(1,len(l)):

key=l[step]

j=step-1

while j>=0 and key<l[j]:

l[j+1],j=l[j],j-1

l[j+1]=key

print("Sorted List:",l)

q=QuickSort()

c=q.inp()

q.quick(c)

48 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:

Thus the above Python program for implementing the concept of Quick sort has been executed
and verified successfully.

49 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

8. IMPLEMENTATION OF SEARCHING ALGORITHMS

8a. LINEAR SEARCH

Aim:

To create a Python class program to implement the concept of linear search.

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:

def linear_search(self,alist, key):

for i in range(len(alist)):

if alist[i] == key:

return i

return -1

def input(self):

alist = input('Enter the list of numbers: ')

alist = alist.split()

alist = [int(x) for x in alist]

key = int(input('The number to search for: '))

return alist,key

50 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

def srh(self,key,index):

if index < 0:

print('{} was not found.'.format(key))

else:

print('{} was found at index {}.'.format(key, index))

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.

51 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

8b. BINARY SEARCH

Aim:

To create a Python class program to implement the concept of binary search.

Algorithm:

Step 1 - Read the search element from the user.


Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate
the function.
Step 5 - If both are not matched, then check whether the search element is smaller or
larger than the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and
5 for the left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5
for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until
sublist contains only one element.
Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.

Program:

class Binary_search:

def binary_search(self,alist, key):

start = 0

end = len(alist)

while start < end:

mid = (start + end)//2

if alist[mid] > key:

end = mid

elif alist[mid] < key:

start = mid + 1

else:

52 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

return mid

return -1

def input(self):

alist = input('Enter the sorted list of numbers: ')

alist = alist.split()

alist = [int(x) for x in alist]

key = int(input('The number to search for: '))

return alist, key

def srh(self,key,index):

if index < 0:

print('{} was not found.'.format(key))

else:

print('{} was found at index {}.'.format(key, index))

bs=Binary_search()

l,k=bs.input()

i=bs.binary_search(l,k)

out=bs.srh(k,i)

53 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:

Thus the Python class program to implement the concept of binary search has been executed
successfully and verified.

54 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

9. IMPLEMENTATION OF HASH TABLE

Aim:

To write a python class program to implement the concept of hashing technique.

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:

55 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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)

56 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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()

57 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:

Thus the python class program to implement the concept of hashing has been executed and
verified successfully.

58 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

10. TREE REPRESENTATION AND TRAVERSAL ALGORITHMS

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)

59 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

60 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

11. BINARY SEARCH TREES

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

61 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

if key < root.key:


root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right, temp.key)
return root
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("Binary Search Tree: ", end=' ')
inorder(root)
print("\nDelete 10")
root = deleteNode(root, 10)
print("Binary Search Tree: ", end=' ')
inorder(root)

62 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:
Thus the Python class program to implement the concept of Binary Search Tree has been
executed and verified successfully.

63 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

12. IMPLEMENTATION OF HEAPS

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:

64 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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()

65 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

66 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

13. GRAPH REPRESENTATION AND TRAVERSAL ALGORITHMS

13a. BREADTH FIRST SEARCH

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:

from queue import Queue


class Graph:
def __init__(self, nodes, is_directed=False):
self.is_directed = is_directed
self.nodes = nodes
self.adj_list = {}
for node in self.nodes:
self.adj_list[node] = []
def print_adj_list(self):
for node in self.nodes:
print("{} -> {}".format(node, self.adj_list[node]))
def add_edge(self, u, v):
self.adj_list[u].append(v)
if not self.is_directed:
self.adj_list[v].append(u)
def add_multiple_edges(self, edges):
for u, v in edges:
self.add_edge(u, v)

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()

67 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

for node in self.adj_list.keys():


self.visited[node] = False
self.parent[node] = None
self.level[node] = -1
def bfs_traversal(self, source):
self.visited[source] = True
self.level[source] = 0
self.queue.put(source)
while not self.queue.empty():
u = self.queue.get()
self.output.append(u)
for v in self.adj_list[u]:
if not self.visited[v]:
self.visited[v] = True
self.parent[v] = u
self.level[v] = self.level[u] + 1
self.queue.put(v)
return self.output
def level_of_node(self, node):
return self.level[node]
def print_path(self, destination):
path = []
while destination is not None:
path.append(destination)
destination = self.parent[destination]
path.reverse()
return path

nodes = ["1", "2", "3", "4", "5"]


edges = [
("1", "3"),
("1", "2"),
("1", "4"),
("2", "3"),
("2", "5"),
("3", "4"),
("3", "5"),
("4", "5"),
]
bfs = BFS(nodes, edges)
source = input("Enter Source : ")
print(bfs.bfs_traversal(source))
destination = input("Enter Destination : ")
print(bfs.print_path(destination))

68 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

Output:

Result:
Thus the Python OOP program to implement the concept of Breadth First Search
using Queue has been executed and verified successfully.

69 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

13b. DEPTH FIRST SEARCH

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):

70 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

return dest in self.points_to

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()

71 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))
print()
elif operation == 'quit':
break

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

14. IMPLEMENTATION OF SINGLE SOURCE SHORTEST PATH ALGORITHM

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 = {}

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):

73 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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):


return dest in self.points_to

def dijkstra(g, source):


unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0

while unvisited != set():


closest = min(unvisited, key=lambda v: distance[v])
unvisited.remove(closest)
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance
return distance

g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('shortest <source vertex key>')

74 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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 == 'shortest':


key = int(do[1])
source = g.get_vertex(key)
distance = dijkstra(g, source)
print('Distances from {}: '.format(key))
for v in distance:
print('Distance to {}: {}'.format(v.get_key(), distance[v]))
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:

75 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

for dest in v.get_neighbours():


w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))
print()

elif operation == 'quit':


break

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.

76 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

15. IMPLEMENTATION OF MINIMUM SPANNING TREE ALGORITHMS

PRIM’S ALGORITHM

Aim:
To write a Python OOP program to implement the concept of Minimum Spanning Tree using
Prim’s algorithm.

Algorithm:

Step 1: Start the process


Step 2: Create classes for Graph and Vertex.
Step 3: Create a function mst_prim that takes a Graph object g as argument.
Step 4: The function will return a Graph object which is a minimum spanning tree of the
graph g.
Step 5: An empty graph called mst is created which will hold a MST of the graph g.
Step 6: The algorithm works by selecting any one vertex from g and adding it to mst.
Step 7: The vertex which is outside mst but has a neighbour in mst with the smallest distance
is added to mst. (If there are multiple such vertices then add any one.)
Step 8: The corresponding edge is also added.
Step 9: The above two steps are repeated until all vertices have been added to the graph.
Step 10: Two dictionaries are used in the above algorithm.
Step 11: The nearest neighbour in mst of a vertex outside mst is kept track of using a
dictionary nearest_neighbour.
Step 12: The corresponding smallest distance is stored in a dictionary called
smallest_distance.
Step 13: Stop the process

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)

77 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

def does_edge_exist(self, src_key, dest_key):


return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])

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 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):


return dest in self.points_to

def mst_prim(g):
mst = Graph()

78 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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>')

79 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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()

elif operation == 'display':


g.display()
print()

elif operation == 'quit':


break

80 E SHAPNA RANI, AP/CSE


Saranathan College of Engineering

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.

81 E SHAPNA RANI, AP/CSE

You might also like