0% found this document useful (0 votes)
24 views32 pages

Dsa Record

Sem -3

Uploaded by

Pandiyan Palani
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)
24 views32 pages

Dsa Record

Sem -3

Uploaded by

Pandiyan Palani
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/ 32

Exp.

No: 1
Simple ADTs As python classes
Date:

Aim:
To Write a python program that appends,delete and displays elements of a list using classes.
Algorithm:
Step 1: Start.
Step 2: Create a class and using a constructor initialize values of that class.
Step 3: Create method for adding,removing and displaying elements.
Step 4: Create an object for the class.
Step 5: Using the object,call the respective function depending on the choice taken from the
user.
Step 6: Print the final list.
Step 7: Stop.
Program:
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return(self.n)
obj=check()
choice=1
while choice!=0:
print("0.Exit")
print("1.Add")
print("2.Delete")
print("3.Display")
choice=int(input("enter choice"))
if choice==1:
n=int(input("enter number to append:"))
obj.add(n)
print("List",obj.dis())
elif choice==2:
n=int(input("enter number to append:"))
obj.remove(n)
print("List",obj.dis())
elif choice==3:
print("list",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("invalid choice")
print()
Result:
The above program is compiled and executed successfully.
Exp. No: 2

Date: Recursive algorithm in python


Aim:
To write a program to take a number and determine the factorial of the number using
recursion.
Algorithm:
Step 1: Start.
Step 2: Take a number from the user and store in a variable.
Step 3: Pass the number as an argument to a recursive factorial function.
Step 4: Define the base condition as the number to be lesser than or equal to 1 and return 1
if it is.
Step 5: Otherwise call the function recursively with the number minus 1 multiplied by the
number itself.
Step 6: Then returns the result and print the factorial of the number.
Step 7: Stop.
Program:
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
N=int(input("Enter a number:"))
f=fact(N)
print("factorial of",N,"is",f)

Result:
The above program is compiled and executed successfully.
Exp. No:3
List ADT using python arrays
Date:

Aim:
To Write a python program for creation and insertion to implement list using an array.
Algorithm:
Step 1: Start
Step 2: Declare the necessary functions for implementation.
Step 3: Get the input from the user and store it an array.
Step 4: In Insertion, half of the elements to be shifted upwards and in deletion half of the
elements to be shifted.
Step 5: Display the output using an array.
Step 6: Stop.
Program:
import array
arr=array.array('i',[1,2,3])
print("The new created array is:",end=" ")
for i in range(0,3):
print(arr[i],end=" ")
print("\r")
arr.append(4)
print("the appended array is:",end=" ")
for i in range(0,4):
print(arr[i],end=" ")
arr.insert(2,5)
print("\r")
print("The array after insertion is:",end=" ")
for i in range(0,5):
print(arr[i],end=" ")

Result:
The above program is compiled and executed successfully.
Exp. No: 4
Linked list implementation of list
Date:

Aim:
To write a python program for traversal , insertion , deletion and search to implement to
implement linked list using list.
Algorithm:
Insert at beginning:
Step 1: Start.
Step 2: Firstly, check if the given previous node is NULL or not.
Step 3: Then, allocate a new node.
Step 4: Assign the data to the new node.
Step 5: Then make the next of new node as the next of previous node.
Step 6: Finally, move the next of the previous node as a new node.
Step 7: Stop.
Insert at middle:
Step 1: Start.
Step 2: Allocate the memory and store data for new node .
Step 3: Traverse to node just before the required position of new node .
Step 4: Change next pointers to include newnode between.
Step 5: Stop.
Insert at end:
Step 1: Start.
Step 2: Allocate memory for newnode.
Step 3: Store the data in the newnode.
Step 4: Traverse to the last node.
Step 5: Change next of last node to recently create created node.
Step 6: Stop.
Delete from beginning:
Step1: point head to the second node.
Delete from end:
Step1: Traverse to second last element.
Step2: Change next pointer to exclude the node from the chain.

Traversal:
Step1: Assign a variable that is pointing to the head node.
Step2: Traverse through the list till current pointing to is null.
Step3: Print each node.

Program:
class node:
def __init__(self,data):
self.data=data
self.next=None
class singlelinklist:
def __init__(self):
self.head=None
self.tail=None
def addnode (self,data):
newnode=node(data)
if(self.head==None):
self.head=newnode
self.tail=newnode
else:
self.tail.next=newnode
self.tail=newnode
def display(self):
current =self.head
if(self.head==None):
print("List is empty")
return
print("Node of single link list:")
while(current !=None):
print (current.data)
current=current.next
slist=singlelinklist()
slist.addnode(1)
slist.addnode(2)
slist.addnode(3)
slist.addnode(4)
slist.display()

Result:
The above program is compiled and executed successfully.
Exp. No:5 a
Implementation of stack
Date:

Aim:
To write a python program creates a stack and allow the user to perform push and pop
operations on it.
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 nodes. 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
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 ypu 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

Result:
The above program is compiled and executed successfully.
Exp. No:5 b
Date: Implementation of Queue

Aim:
To write a python program creates a queue and allows the user to perform enqueue and
dequeue operations on it.

Algorithm:
Step 1: 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

Result:
The above program is compiled and executed successfully.
Exp. No:6
Date:
APPLICATIONS OF LIST, STACK AND QUEUE

A. APPLICATIONS OF LIST ADT


Aim:
To write a Python program for implementation of polynomial ADT.
Algorithm:
Step 1: Start the program
Step 2: Get the coefficients and powers for the two polynomials to be added.
Step 3: Add the coefficients of the respective powers.
Step 4: Display the added polynomial.
Step 5: Terminate the program.
Program:
def add(A, B, m, n):
size = max(m, n);
sum = [0 for i in range(size)]
for i in range(0, m, 1):
sum[i] = A[i]
for i in range(n):
sum[i] += B[i]
return sum
def printPoly(poly, n):
for i in range(n):
print(poly[i], end ="")
if (i != 0):
print("x^", i, end ="")
if (i != n - 1):
print("+", end ="")
if __name__ =='__main__':
A = [5, 0, 10, 6]
B = [1, 2, 4]
m = len(A)
n = len(B)
print("First polynomial is")
printPoly(A, m)
print("\n", end = "")
print("Second polynomial is")
printPoly(B, n)
print("\n", end ="")
sum = add(A, B, m, n)
size = max(m, n)
print("sum polynomial is")
printPoly(sum, size)
Result:
Thus, the Python program for implementation of polynomial ADT has been executed
Successfully.
B. APPLICATIONS OF STACK ADT
Aim:
To write a Python program to Check if Expression is Correctly Parenthesized
Algorithm:
Step 1: Start.
Step 2: Create a class Stack with instance variable items initialized to an empty list.
Step 3: Define methods push, pop and is_empty inside the class Stack.
Step 4: The method push appends data to items.
Step 5: The method pop pops the first element in items.
Step 6: The method is_empty returns True only if items is empty.
Step 7: Prompt the user for an expression.
Step 8: Iterate through the characters of the expression and push to the stack if an open
parenthesis is encountered and pop if a close parenthesis is encountered.
Step 9: Determine whether the expression has balanced parentheses.
Step 10: Stop
Program:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
s = Stack()
exp = input("Please enter the expression:")
for c in exp:
if c =='(':
s.push(1)
elif c ==')':
if s.is_empty():
is_balanced = False
break
s.pop()
else:
if s.is_empty():
is_balanced = True
else:
is_balanced = False
if is_balanced:
print("Expression is correctly parenthesized")
else:
print("Expression is not correctly parenthesized")

Result:
Thus, the Python program for implementation of whether Expression is Correctly
Parenthesized has been executed successfully.
C. APPLICATIONS OF QUEUE ADT
Aim:
To write a Python program that creates a dequeue and allows the user to perform append and
pop operations on it from both sides.
Algorithm:
Step 1: Start.
Step 2: Create a class Dequeue with instance variable items initialized to an empty list.
Step 3: Define methods append, append_left, pop, pop_left and is_empty inside the class
Dequeue.
Step 4: The method append appends data to items from the right.
Step 5: The method append_left appends data to items from the left.
Step 6: The method pop pops from the right from items.
Step 7: The method pop_left pops from the left from items.
Step 8: The method is_empty returns True only if items is empty.
Step 9: Stop.
Program:
class Dequeue:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def append(self, data):


self.items.append(data)

def append_left(self, data):


self.items.insert(0, data)

def pop(self):
return self.items.pop()

def pop_left(self):
return self.items.pop(0)
q = Dequeue()
print('Menu')
print('append <value>')
print('appendleft <value>')
print('pop')
print('popleft')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'append':
q.append(int(do[1]))
elif operation == 'appendleft':
q.append_left(int(do[1]))
elif operation == 'pop':
if q.is_empty():
print('Dequeue is empty.')
else:
print('Popped value from right: ', q.pop())
elif operation == 'popleft':
if q.is_empty():
print('Dequeue is empty.')
else:
print('Popped value from left: ', q.pop_left())
elif operation == 'quit':
break

Result:
Thus, the Python program for implementation of dequeue and allows the user to
perform append and pop operations on it from both sides. has been executed successfully.
Exp. No: 7
Date:
SORTING AND SEARCHING ALGORITHMS

A. SORTING ALGORITHM (INSERTION SORT):


Aim:
To Perform Insertion Sorting in Python Programming.
Algorithm:
Step 1: Start.
Step 2: Define list of elements(alist).
Step 3: Take first element find its appropriate position and insert them.
Step 4: Repeat till every element is sorted.
Step 5: Print the list of elements.
Step 6: Stop.
Program:
def insertionSort(lst):
for index in range(1, len(lst)):
currentvalue = lst[index]
position = index
while position > 0 and lst[position - 1]> currentvalue:
lst[position] = lst[position - 1]
position = position - 1
lst[position] = currentvalue
lst = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insertionSort(lst)
print(lst)

Result:
The above program to implement sequential search is executed and verified successfully.
B. SEARCHING ALGORITHM (LINEAR SEARCH)
Aim:
To Perform a Linear Search in Python Programming
Algorithm:
Step 1: Start.
Step 2: Define a list of elements list_of_elements[].
Step 3: Get the element to be checked from the user(x).
Step 4: Compare the elements with each element in the list.
Step 5: If found print found and print index number.
Step 6: Else print element not found.
Step 7: Stop.
Program:
list_of_elements = [4, 2, 8, 9, 3, 7]
x = int(input("Enter number to search:"))
found = False
for i in range(len(list_of_elements)):
if(list_of_elements[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break
if(found == False):
print("%d is not in list"%x)

Result:
Thus, the python program to perform Linear Search is created and executed
successfully.
Ex. No: 8
HASH TABLE
Date:
Aim:

To write a python program to implement the concept of hashing using separate chaining.

Algorithm:

Step 1: Start
Step 2: Create Table size
Step 3: Create hash function
Step 4: To insert a node into the hash table, we need to find the hash index for the given key.
and it could be calculated using the hash function.
Step 5: Display hash entry.
Step 6: Stop

Program:

def display_hash(hashTable):

for i in range(len(hashTable)):

print(i, end = " ")

for j in hashTable[i]:

print("-->", end = " ")

print(j, end = " ")

print()

HashTable = [[] for _ in range(10)]

def Hashing(keyvalue):

return keyvalue % len(HashTable)

def insert(Hashtable, keyvalue, value):

hash_key = Hashing(keyvalue)

Hashtable[hash_key].append(value)
insert(HashTable, 10, 'Allahabad')

insert(HashTable, 25, 'Mumbai')

insert(HashTable, 20, 'Mathura')

insert(HashTable, 9, 'Delhi')

insert(HashTable, 21, 'Punjab')

insert(HashTable, 21, 'Noida')

display_hash (HashTable)

Result:
Thus, the python program to implement the concept of hashing using separate chaining has
been implemented successfully.
Exp. No: 9
Date: TREE REPRESENTATION AND TRAVERSAL

Aim:
To write a python program to implement the tree representation and traversal algorithm.

ALGORITHM:
Step 1: Start.
Step 2: The left sub tree of a node contains smaller nodes than a root node.
Step 3: The right sub tree of a node contains greater nodes than a root node.
Step 4: Both the left and right sub trees must also be binary search trees.
Step 5: There are three types of tree traversals: Preorder, Postorder, and Inorder.
Step 6: Stop.

Pre-order traversal:
Visit the root node before (pre) visiting the left and right subtree.
Algorithm:
Step 1: Start.
Step 2: Visit the root (we will print it when we visit to show the order of visiting).
Step 3: Traverse the left subtree in pre-order.
Step 4: Traverse the right subtree in pre-order.
Step 5: Stop.

In-order traversal:
Visit the root node in between the left and right node (in).
Algorithm:
Step 1: Start.
Step 2: Traverse the left subtree in in-order.
Step 3: Visit the root (we will print it when we visit to show the order of visiting).
Step 4: Traverse the right subtree in in-order.
Step 5: Stop.

Post-order traversal:
Visit the root node after (post) visiting the left and right subtree.
Algorithm:
Step 1: Start.
Step 2: Traverse the left subtree in in-order.
Step 3: Traverse the right subtree in in-order.
Step 4: Visit the root (we will print it when we visit to show the order of visiting).
Step 5: Stop.

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)

Result:
The above program to implement the tree representation and traversal algorithm is
executed and verified successfully.
Exp. No: 10
Date: IMPLEMENTATION OF BINARY SEARCH TREES

Aim:
To write a python program to implement Binary Search Trees.
Algorithm:
Step 1: Start.
Step 2: The left sub tree of a node contains smaller nodes than a root node.
Step 3: The right sub tree of a node contains greater nodes than a root node.
Step 4: If the value to be inserted is less than the node, we will traverse its left subtree
recursively.
Step 5: We traverse the right subtree recursively when the value to be inserted is greater
than the node.
Step 6: If the node is empty, We will create a node and insert the value.
Step 7: If the node to be deleted is the leaf node. In such a case, simply delete the node
from the tree.
Step 8: If the node to be deleted lies has a single child node then,
Step 9: Replace that node with its child node and remove the child node from its original
position.
Step 10: If the node to be deleted has two children then,
Step 11: Get the inorder successor of that node then replace the node with the inorder
successor and remove the inorder successor from its original position.
Step 12: Stop.
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 preorder(root):
if root is not None:
print(str(root.key)+ "->", end=' ')
preorder(root.left)
preorder(root.right)
def postorder(root):
if root is not None:
postorder(root.left)
postorder(root.right)
print(str(root.key)+ "->", end=' ')
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 deleteNode(root, key):
if root is None:
return root
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("\nInorder traversal: ", end=' ')
inorder(root)
print("\nDelete 14")
root = deleteNode(root, 14)
print("\nInorder traversal: ", end=' ')
inorder(root)
print("\npreoder traversal: ", end=' ')
preorder(root)

print("\nDelete 10")
root = deleteNode(root, 10)
print("\npreorder traversal: ", end=' ')
preorder(root)
print("\npostorder traversal: ", end=' ')
postorder(root)

print("\nDelete 8")
root = deleteNode(root, 8)
print("\npostorder traversal: ", end=' ')
postorder(root)

Result:
The above program to implement Binary Search Trees is executed and verified
successfully.
Exp. No: 11
Date:
IMPLEMENTATION OF HEAPS

AIM:
To write a python program to implement Heaps.

ALGORITHM:

MAX HEAP:
Step 1: Start
Step 2: Create a new node at the end of the heap.
Step 3: Assign new value to the node.
Step 4: Compare the value of this child node with its parent.
Step 5: If value of parent is less than child, then swap them.
Step 6: Repeat step 3 & 4 until Heap property holds.
Step 7: Stop

MIN HEAP:
Step 1: Start
Step 2: Create a new node at the end of the heap.
Step 3: Assign new value to the node.
Step 4: Compare the value of this child node with its parent.
Step 5: If value of parent is greater than child, then swap them.
Step 6: Repeat step 3 & 4 until Heap property holds.
Step 7: Stop

PROGRAM:

//MAX HEAP
def max_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] > A[k]:
largest = l
else:
largest = k
if r < len(A) and A[r] > A[largest]:
largest = r
if largest != k:
A[k], A[largest] = A[largest], A[k]
max_heapify(A, largest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_max_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
max_heapify(A,k)
//MIN HEAP
def min_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] < A[k]:
smallest = l
else:
smallest = k
if r < len(A) and A[r] < A[smallest]:
smallest = r
if smallest != k:
A[k], A[smallest] = A[smallest], A[k]
min_heapify(A, smallest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_min_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
min_heapify(A,k)
A = [3,9,2,1,4,5]
build_min_heap(A)
print("MIN HEAP :",A)
A = [3,9,2,1,4,5]
build_max_heap(A)
print("MAX HEAP :",A)

RESULT:
The above program to implement Heaps is executed and verified successfully.
Exp No:12
Date:
GRAPH REPRESENTATION AND TRAVERSAL
ALGORITHMS

AIM :
To write a python program to implement Graph Representation and Traversal.

ALGORITHM:

DEPTH FIRST SEARCH:


Step 1: Start
Step 2: First, create a stack with the total number of vertices in the graph.
Step 3: Now, choose any vertex as the starting point of traversal, and push that vertex into
the stack.
Step 4: After that, push a non-visited vertex (adjacent to the vertex on the top of the stack)
to the top of the stack.
Step 5: Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex on the
stack's top.
Step 6: If no vertex is left, go back and pop a vertex from the stack.
Step 7: Repeat steps 2, 3, and 4 until the stack is empty.
Step 8: Stop

BREADTH FIRST SEARCH:


Step 1: Start
Step 2: Start by putting any one of the graph’s vertices at the back of the queue.
Step 3: Now take the front item of the queue and add it to the visited list.
Step 4: Create a list of that vertex's adjacent nodes. Add those which are not within the
visited list to the rear of the queue.
Step 5: Keep continuing steps two and three till the queue is empty.
Step 6: Stop

PROGRAM :

DEPTH FIRST SEARCH:


class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
# Check for the visisted and unvisited nodes
def dfs(graph, start, visited = None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
dfs(gdict, 'a')

BREATH FIRST SEARCH:


import collections
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def bfs(graph, startnode):
# Track the visited and unvisited nodes using queue
seen, queue = set([startnode]), collections.deque([startnode])
while queue:
vertex = queue.popleft()
marked(vertex)
for node in graph[vertex]:
if node not in seen:
seen.add(node)
queue.append(node)

def marked(n):
print(n)

RESULT:
The above program to implement Graph Representation and Traversal is executed and
verified successfully.
Exp No:13
Date:
IMPLEMENTATION OF SINGLE SOURCE SHORTEST
PATH ALGORITHM

AIM :
To write a python program to implement Single Source Shortest Path Algorithm.

ALGORITHM:
Step 1: Start
Step 2: Initialize the starting node with 0 costs and the rest of the node as Infinity Cost.
Step 3: Maintain an array or list to keep track of the visited nodes
Step 4: Update the node cost with the minimum cost. It can be done by comparing the
current cost with the path cost. (Demonstration is shown in the example section)
Step 5: Continue step 3 until all the node is visited.
Step 6: Stop

PROGRAM:
num_of_vertex = 7
def minimumDistance(distance, visited):
_min = 1e11
min_index = 1e11
for i in range(num_of_vertex):
if not visited[i] and distance[i] & lt; = _min:
_min = distance[i]
min_index = i
return min_index
def printParentNode(parent, i):
if parent[i] == -1:
return
printParentNode(parent, parent[i])
print("{} ".format(i + 1), end = "")
def dijkstra(graph, src):
distance = list()
visited = list()
parent = list()
for i in range(num_of_vertex):
parent.append(-1)
distance.append(1e11)
visited.append(False)
distance[src] = 0
for i in range(num_of_vertex - 1):
U = minimumDistance(distance, visited)
visited[U] = True
for j in range(num_of_vertex):
curr_distance = distance[U] + graph[U][j]
if not visited[j] and graph[U][j] and curr_distance & lt;
distance[j]: parent[j] = U
distance[j] = curr_distance
print("Vertex\t\tDistance\tPath")
for i in range(num_of_vertex):
print("{}->{}\t\t{}\t\t{}
".format(src + 1, i + 1, distance[i], src + 1), end = "")
printParentNode(parent, i)
print("")
graph = [
[0, 1, 7, 6, 0, 0, 0],
[1, 0, 9, 0, 0, 3, 0],
[7, 9, 0, 0, 0, 0, 1],
[6, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 3, 0, 0, 0, 0, 3],
[0, 0, 0, 0, 5, 3, 0]
]
dijkstra(graph, 0)

RESULT:
The above program to implement Single Source Shortest Path Algorithm is executed
and verified successfully.
Exp No: 14
Date:
IMPLEMENTATION OF MINIMUM SPANNING TREE
ALGORITHMS

AIM:
To write a python program to implement Minimum Spanning Tree.

ALGORITHM:
Step 1: Start
Step 2: Sort the graph edges with respect to their weights.
Step 3: Start adding edges to the MST from the edge with the smallest weight until the
edge of the largest weight.
Step 4: Only add edges which doesn't form a cycle , edges which connect only
disconnected components.
Step 5: Stop

PROGRAM:
class Graph:
def __init__(self, vertex):
self.V = vertex
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def search(self, parent, i):
if parent[i] == i:
return i
return self.search(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.search(parent, x)
yroot = self.search(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i=i+1
x = self.search(parent, u)
y = self.search(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("Edge:",u, v,end =" ")
print("-",weight)

g = Graph(5)
g.add_edge(0, 1, 8)
g.add_edge(0, 2, 5)
g.add_edge(1, 2, 9)
g.add_edge(1, 3, 11)
g.add_edge(2, 3, 15)
g.add_edge(2, 4, 10)
g.add_edge(3, 4, 7)
g.kruskal()

RESULT:
The above program to implement Single Source Minimum Spanning Tree is executed
and verified successfully.

You might also like