Data Structures - Reg 2021
Data Structures - Reg 2021
Aim:-
To write program to implement simple adts in python classes.
Algorithm:-
Step 1:- start
Step 2:- create class rectangle
Step 3:- create methods like area and perimeter
Step 4:- declare breadth and length
Step 5:- create object for rectangle
Step 6:- call member function area and perimeter from class rectangle.
Step 7:-stop
Program:-
class Rectangle():
def_int_(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
print(self.breadth*self.length)
def perimeter(self):
print(2*(self.breadth+self.length))
a=int(input("Enter length of the rectangle: "))
b=int(input("Enter breadth of the rectangle: "))
obj=Rectangle (a,b)
print("Area of rectangle ")
obj.area()
print("perimeter of rectangle")
obj.perimeter()
Output:-
Enter length of the rectangle: 3
Enter breadth of the rectangle: 2
Area of rectangle:
6
Perimeter of rectangle:
10
2) Implement recursive algorithms in Python
Aim:-
To write program to print a sequence of fibonacci using recursion.
Algorithm:-
Step 1:- start
Step 2:- declare function called Fibonacci
Step 3:-declare n for number of terms.
Step 4:-print the sequence of number
Step 5:- stop
Program:-
def Fibonacci(n):
if (n <=1):
return n
else:
return (fibonacci (n-1) + fibonacci (n-2))
print ("Enter number of terms")
n=int (input ())
print("fibonacci sequence is as follows...")
for i in range (n):
print (fibonacci (i))
Output:-
Enter number of terms
15
fibonacci sequence is as follows...
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
3) LIST ADT USING DOUBLY LINKED LIST
AIM :-
To Write A Python Program To Execute The Doubly Linked Lists
ALGORITHM:-
STEP 1: Start
STEP 2: Create a class
STEP 3: Create a header node and last node
STEP 4: Accept the user choice Insert, Delete and Display
STEP 5: Insert the new node
STEP 6: Delete the node from the list
STEP 7: Display the node
STEP 8: Stop
PROGRAM:-
Class Node:
Def init (self, data):
Self.item = data
Self.next = None
Self.prev = None
Class doublyLinkedList:
Def init (self):
Self.start_node = None
Def InsertToEmptyList(self, data):
If self.start_node is None:
New_node = Node(data)
Self.start_node = new_node
Else:
Print(“The list is empty”)
Def InsertToEnd(self, data):
If self.start_node is None:
New_node = Node(data)
Self.start_node = new_node
Return
N = self.start_node
While n.next is not None:
N = n.next
New_node = Node(data)
n.next = new_node
new_node.prev = n
Def DeleteAtStart(self):
If self.start_node is None:
Print(“The Linked list is empty, no element to delete”)
Return
If self.start_node.next is None:
Self.start_node = None
Return
Self.start_node = self.start_node.next
Self.start_prev = None;
Def delete_at_end(self):
If self.start_node is None:
Print(“The Linked list is empty, no element to delete”)
Return
If self.start_node.next is None:
Self.start_node = None
Return
N = self.start_node
While n.next is not None:
N = n.next
n.prev.next = None
Def Display(self):
If self.start_node is None:
Print(“The list is empty”)
Return
Else:
N = self.start_node
While n is not None:
Print(“Element is: “, n.item)
N = n.next
Print(“\n”)
NewDoublyLinkedList = doublyLinkedList()
NewDoublyLinkedList.InsertToEmptyList(10)
NewDoublyLinkedList.InsertToEnd(20)
NewDoublyLinkedList.InsertToEnd(30)
NewDoublyLinkedList.InsertToEnd(40)
NewDoublyLinkedList.InsertToEnd(50)
NewDoublyLinkedList.InsertToEnd(60)
NewDoublyLinkedList.Display()
NewDoublyLinkedList.DeleteAtStart()
NewDoublyLinkedList.DeleteAtStart()
NewDoublyLinkedList.Display()
OUTPUT:-
4) Linked List Implementations of List
Aim:
To Write a python program to implement Linked List
Algorithm:
Step1: Start
Step2: Create class Node
Step3: Create class SLL
Step4: Insert the element in the list
Step5: Display the element you want to delete
Step6: Display the element present in the linked list
Step7: Stop
Program:
class Node:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class SLL:
def __init__(self):
self.head=None
def create(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
while(temp.next):
temp=temp.next
temp.next=newNode
else:
self.head=newNode
def display(self):
temp=self.head
while(temp):
s=str(temp.data)+"->"
print(s,end=" ")
temp=temp.next
print("NULL")
def insert_head(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
newNode.next=temp
self.head=newNode
else:
self.head=newNode
def insert_last(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
while(temp.next):
temp=temp.next
temp.next=newNode
else:
self.head=newNode
def insert(self,data):
newNode=Node(data)
print("After which node do you want to insert?");
middle_element=int(input())
if(self.head):
temp=self.head
while(temp.data!=middle_element):
temp=temp.next
newNode.next=temp.next
temp.next=newNode
else:
self.head=newNode
def delete(self):
temp=self.head
if(self.head==None):
print("The linked list is empty")
else:
print("Enter the element you want to delete:")
key=int(input())
while(temp.data!=key):
prev=temp
temp=temp.next
prev.next=temp.next
temp=None
def search(self):
temp=self.head
if(self.head==None):
print("The linked list is empty")
else:
print("Enter the element you want to search:")
key=int(input())
found=False
while(temp and found==False):
if(temp.data!=key):
temp=temp.next
else:
found=True
if(found):
print("The element is present in the linked list")
else:
print("The element is not present in the linked list")
obj=SLL()
obj.create(10)
obj.create(20)
obj.create(30)
print("The linked list is…")
obj.display()
obj.insert_head(9)
obj.display()
obj.insert_last(40)
obj.display()
obj.insert(35)
obj.display()
obj.delete()
obj.display()
obj.search()
Output:
5)i) Implementation of Stack ADT
Aim:-
To write program to implement stack ADT using python.
Algorithm:-
Step 1:- start
Step 2:- declare a empty stack.
Step 3:-print the options available in stack.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like push,pop and display
Step 6:-stop
Program:-
# Program introduction statement
print("Simple STACK Data Structure Program")
# Initial empty STACK
stack = []
# Display Menu with Choices
while True:
print("\nSELECT APPROPRIATE CHOICE")
print("1. PUSH Element into the Stack")
print("2. POP Element from the Stack")
print("3. Display Elements of the Stack")
print("4. Exit")
choice = int(input("Enter the Choice:")) # Taking input from the user regarding choice
# USER enter option 1 then PUSH elements into the STACK
if choice == 1:
# append() function to PUSH elements into the STACK
stack.append("Monday") # PUSH element Monday
stack.append("Tuesday") # PUSH element Tuesday
stack.append("Wednesday") # PUSH element Wednesday
stack.append("Thursday") # PUSH element Thursday
stack.append("Friday") # PUSH element Friday
stack.append("Saturday") # PUSH element Saturday
stack.append("Sunday") # PUSH element Sunday
stack.append('8') # PUSH element 8
print('\nTotal 8 elements PUSH into the STACK')
# USER enter option 2 then POP one element from the STACK
elif choice == 2:
if len(stack) == 0: # Check whether STACK is Empty or not
print('The STACK is EMPTY No element to POP out')
# Display this ERROR message if STACK is Empty
else:
# pop() function to POP element from the STACK in LIFO order
print('\nElement POP out from the STACK is:')
print(stack.pop()) # Display the element which is POP out from the STACK
Algorithm:-
Step 1:- start
Step 2:- declare a empty queue.
Step 3:-print the options available in queue.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like enqueue,dequeue and display
Step 6:-stop
Program:-
# Python program to
# demonstrate implementation of
# queue using queue module
from queue import Queue
# Initializing a queue
q = Queue(maxsize = 3)
# qsize() give the maxsize
# of the Queue
print(q.qsize())
q.put('a')
q.put('b')
q.put('c')
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
Output:-
>>>
Full: True
Empty: True
Empty: False
Full: False
Result:-
Thus the python program was executed and the output was verified successfully.
6)A) APPLICATIONS OF LIST
AIM :
ALGORITHM :
STEP 1:Start
STEP 5:Read the number of terms of A polynomial in variable t1 and read the numbers of the
terms of A polynomial in variable 2.
STEP 6:.if exponent at ith position of A poly is equal to the exponent at jth position of
polynomial B then ,
STEP 6.1;Add the coefficients at that position from both the polynomial and store the
result in C arrays coefficient field at position k copy the exponent either pointed by i or
j at position k in C array.
STEP 6.2;Increment i, j and k to point to the next position in the array A, B and C.
STEP 6.3: Copy the coefficient at position j of B polynomial into coefficient field at
position k in C array.
STEP 6.4: Copy the exponent pointed by j into exponent field at position k in C array.
STEP 6.5: Increment j and k pointers to point to the next position in array B and C.
STEP 7: Copy the coefficient at position i of into the coefficient field at position k in C.
STEP 7.1: Copy the exponent pointed by i into the exponent field at position k in C
array.
STEP 7.2: Increment i and k to point to the next position in arrays A and C.
STEP 8: Copy the coefficient at position j of B into the coefficient field at position k
in C.
STEP 8.1: Copy the exponent pointed by j into exponent field at position k in C.
STEP 11:End
PROGRAM :
class node:
def add(A, B, m, n):
size = max(m, n);
C=[0 for i in range(size)]
for i in range(0, m, 1):
C[i] = A[i]
for i in range(n):
C[il + B[i]
return C
def display(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 = [1, 1, 2, 3]
B = [0, 7,0, 5]
m = len(A)
n=len(B)
print("\nFirst polynomial is")
display(A, m)
print("\nSecond polynomial is")
display(B, n)
C=add(A, B, m, n)
size = max(m, n)
print("\n Addition of polymomial is'")
display(C, size)
OUTPUT :
6) b) Application of stack
Aim:
To write a python program for converting infix expression to postfix
form.
Algorithm:
Step 1: start
Step 2: create class as InfixPostfix
Step 3: check if the stack is empty
Step 4: return the top of the value of the stack
Step 5: pop the element from the stack
Step 6: then push the element to the stack
Step 7: check is the given character is operand
Step 8: check precedence of operator is less than top of stack or not
Step 9: use conditional statements
Step 10: declare a as self.pop()
Step11: declare s as *.join(self.postfix)
Step12:print (s)
Step13:print infix expression
Step14: stop.
Program:
class InfixPostfix:
def_init_(self):
self.top + -1
self.stack = []
self.postfix = []
self.precedence = {'+':1,
'-':1,
'.':2,
'/':2,
'^':3}
def isEmpty(self)
if(self.top == -1):
return True
else:
False
def peek(self):
return self.stack{-1}
def pop(self):
if not self.isEmpty():
self.top .= 1
return self.stack.pop()
else:
return "$"
def push(self,op):
self.top +=1
self.stack.append(op)
def notGreater(self,i):
try:
a = self.precedence{i}
b = self.precedence{self.peek()}
if a <= b:
return True
else:
return False
except KeyError:
return False
def convert(self,exp):
for ch in exp:
if self.isOperand(ch):
self.postfix.append(ch)
elif ch == '(':
self.push(ch)
elif ch == ')':
while((not self.isEmpty()) and self.peek()!= '('):
a = self.pop()
self.postfix.append(a)
if(not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()
else:
while(not self.isEmpty() and self.notGreater(ch)):
self.postfix.append(self.pop())
self.push(ch)
while not self.isEmpty():
self.postfix.append(self.pop())
s = *.join(self.postfix)
print(s)
print("*program for conversion of infix to postfix*")
print("enter infix expression:")
exp = input()
obj = InfixPostfix()
print("the postfix expression is...")
obj.convert(exp)
Output:
Algorithm:-
Step 1:- start
Step 2:- declare a empty queue.
Step 3:-print the options available in queue.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like enqueue,dequeue and display
Step 6:-stop
Program:-
class MyCircularQueue():
def __init__(self, k):
self.k = k
self.queue = [None] * k
self.head = self.tail = -1
# Insert an element into the circular queue
def enqueue(self, data):
if ((self.tail + 1) % self.k == self.head):
print("The circular queue is full\n")
elif (self.head == -1):
self.head = 0
self.tail = 0
self.queue[self.tail] = data
else:
self.tail = (self.tail + 1) % self.k
self.queue[self.tail] = data
# Delete an element from the circular queue
def dequeue(self):
if (self.head == -1):
print("The circular queue is empty\n")
elif (self.head == self.tail):
temp = self.queue[self.head]
self.head = -1
self.tail = -1
return temp
else:
temp = self.queue[self.head]
self.head = (self.head + 1) % self.k
return temp
def printCQueue(self):
if(self.head == -1):
print("No element in the circular queue")
AIM:
To write a python program to implement binary search
ALGORITHM:
Step 1: start
Step 5:stop
PROGRAM :-
# Binary Search in python
if array[mid] == x:
return mid
else:
else:
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x=4
if result != -1:
else:
print("Not found")
OUTPUT:
7)B)LINEAR SEARCH
AIM:
To write a python program to implement linear search
ALGORITHM:
Step 1: start
Step 5:stop
PROGRAM :-
def linearSearch(array, n, x):
if (array[i] == x):
return i
return -1
array = [2, 4, 0, 1, 9]
x=1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
else:
>>>
Element found at index: 3
7)C) Quick Sort
Aim:-
To write a python program to sort a list of elements using Quick sort.
Algorithm:
Step 1: start
Step 2:Input the elements of the list
Step 2: Display “Array before sorting”
Step 3: Repeat the following from i is equal to 0 until i is lesser than equal to high
Step 3.1: Display the value of a[i]
Step 4: Call quicksort()
Step 5: Display “Array after sorting”
Step 6: Display the sorted elements
Step 7: End
Program:-
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
Output:-
7)d) IMPLEMENTATION OF MERGE SORT
Aim:-
To write a python program to implement merge sort.
Algorithm:-
Step 1: Input the total number of elements
Step 6: Return 0
Step 7: End
Step 6:End
Step 4: Repeat the following until left is lesser than equal to mid and right is lesser than
equal to high
Step 5.1:Then repeat the following from i = right till i is lesser than equal to high
5.2: If not repeat the following from i is equal tp left till i is lesser than equal to mid Step
Step 6:Repeat the following from i is equal to 0 till is lesser than equal to (high-low)
Step 7: End
Program:
def mergeSort(array):
if len(array) > 1:
r = len(array)//2
L = array[:r]
M = array[r:]
mergeSort(L)
mergeSort(M)
i=j=k=0
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
print("Sorted array is: ")
printList(array)
Output:
Sorted array is:
1 5 6 9 10 12
7)e) IMPLEMENTATION OF INSERTION SORT
Aim:-
To write a python program to implement insertion Sort.
Algorithm:-
Step 1: start
Step 7: End
Program:
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is
found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
# Place key at after the element just smaller than it.
array[j + 1] = key
data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]
8)Implementation of Hash tables
Aim:-
To write program to Implementation of Hash tables.
Algorithm:-
Step 1:- start
Step 2:- declare a function display and linear_prob
Step 3:-declare hash table variable ad empty.
Step 4:-enter hash value in hash table.
Step 5:- display hash table
Step 6:-stop
Program:-
def display(a,n):
print("……………….")
print(" Hash Table ")
print("……………….")
for i in range(n):
print(i, "\t",a[i])
def Linear_prob(table,tsize,num):
key=num%tsize
while(table[key]!=-1):
key=(key+1)%tsize
table[key]=num
display(table,tsize)
SIZE=10;
hash_table=[];
print("Handling Hash Table Using Linear Problem")
i=0
for i in range(SIZE):
hash_table.append(-1)
ans= "y"
while ans== "y":
print("\n Enter The Number:")
num=int(input())
Linear_prob(hash_table,SIZE,num)
print("\n Do U Wish To Continue?(y/n)")
ans=input()[0]
Output:-
>>>
Handling Hash Table Using Linear Problem
Do U Wish To Continue?(y/n)
Result:-
Thus the python program was executed and the output was verified successfully.
9) Tree representation and traversal algorithms
Aim:-
To write program to Implementation of Tree representation and traversal algorithms.
Algorithm:-
Step 1:- start
Step 2:- declare a function insert,inorder,preoder and postorder
Step 3:-show the available methods in program.
Step 4:-enter yr choice of method.
Step 5:- according to choice do the process.
Step 6:-stop
Program:-
class Node:
def init_(self, data):
self.valdata
self.left = None
self.right =None
def insert(root, data):
ch=""
if root is None:
return Node(data)
else:
print("Current node is: ",root.val," Where to attach a node?")
print(" If as a left child, press 1")
print(" If as a right child press r")
ch= input()[0]
if(ch=='r'):
root.right = insert(root.right, data)
elif (ch == 1):
root.left = insert(root.left, data)
else:
return root
return root
#The inorder function
def inorder(root):
if root:
inorder(root.left)
print(root.val,end="")
inorder(root.right)
def preorder(root):
if root:
printfroot.val.end=""
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val,end="")
#Driver Code
print("Program for Implementation of Binary Search Tree")
I = None
ans = 'Y'
while(True):
print("in Main Menu")
print("1.Create")
print("2 Inorder")
print("3.Preorder")
print("4.Postorder")
print("Enter your choice: ")
choice = int(input())
if choice == 1:
while(ans =='Y'):
print("Enter the element: ")
num= int(input())
if(r==None):
r = Node(num)
else:
r=insert(r, num)
print("Do you want to continue?")
ans=input()[0]
elif choice == 2:
print("\n The inorder traversal is...")
inorder(r)
elif choice==3:
print("\n The preorder traversal is...")
preorder(r)
elif choice==4:
print("\n The postorder traversal is...")
postorder(r)
else:
print("Good Bye")
break
Output:-
>>>
Program for Implementation of Binary Search Tree
in Main Menu
1.Create
2 Inorder
3.Preorder
4.Postorder
Enter your choice:
10
Good Bye
Result:-
Thus the python program was executed and the output was verified successfully.
10)IMPLEMENTATION OF BINARY SEARCH
TREE
AIM:
ALGORITHM:
STEP 1: Start
STEP 2: Create a newNode with given value and set its left and right to “None”.
STEP5: If the tree is Not Empty, then check whether value of newNode is smaller or largerthan
the node (here it is root node).
STEP 6: If newNode is smaller than or equal to the node, then move to its left child. If
newNode is larger than the node, then move to its right child.
STEP 7: Repeat the above step until we reach to a leaf node (ie., reach to “None”).
STEP 8: After reaching a leaf node, then insert the newNode as left child if newNode is
smaller else insert it as right child.
STEP 10: Compare, the search element with the value of root node in the tree.
STEP 11: If both are matching, then display "Given node found!!!" and terminate the function
STEP 12: If both are not matching, then check whether search element is smaller or larger than
that node value.
STEP 13: If search element is smaller, then continue the search process in left subtree.
STEP 14: If search element is larger, then continue the search process in right subtree.
STEP 15: Repeat the same until we found exact element or we completed with a leaf node
PROGRAM:
class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
inorder(r)
OUTPUT:
RESULT:
Thus the python program to implement the Binary Search Tree was successfully
implemented and output is verified.
11) Implement Insertion Operation Of Heap In Python.
Aim:
To Write A Program To Implement A Heaps
Algorithm:
Step 1: Start
Step 2: Use Def Function
Step 3: Use Heap As Module
Step 4: Use If Condition
Step 5: Stop
Program:-
def heapify(Heap,n,i):
parent = int((i - 1)/ 2)
if (Heap[parent] > 0):
if (Heap[i]> Heap[parent]):
temp = Heap[i]#swap them
Heap[i]= Heap[parent]
Heap[parent]= temp
heapify(Heap,n,parent)
def Insert(Heap,Key):
global n
n =n+ 1 #size of heap is increased by 1
Heap.append(Key)
heapify(Heap,n,n-1)
def display(Heap,n):
print(Heap)
#Driver Code
a = []
print("\n Creating a heap")
print("\nHow many elements are there? ")
n = int(input())
for i in range(n):
print("\n Enter the elements: ")
num=int(input())
a.append(num)
print(" The heap is as follows...\n")
display(a, n)
print(" Enter the element to be inserted in the heap: ")
key = int(input())
Insert(a,key)
print(" After insertion the heap is as follows.....\n")
display(a, n)
Output:-
Creating a heap
[1, 2, 3, 4, 5]
Enter the element to be inserted in the heap:
Result:-
Thus the python program for is executed successfully and output is verified.
12) Graph Representation And Traversal Algorithms
Aim:-
Algorithm:-
Step1: Start.
Step2: Pick any node ,visit the adjacent unvisited vertex, mark it as
Step4: Repeat step1 and step2 until the queue is empty or the desired
node is found.
Step5: Stop.
Program:-
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
v1=queue.pop(0)
print(v1,end=" ")
for v2 in graph[v1]:
if v2 not in visited:
visited.append(v2)
queue.append(v2)
graph={'1':['2','3'],'2':['1','4'],'3':['1','4'],'4':['2','3']}
visited=[ ]
queue=[ ]
n=len(graph)
i=1
for i in range(n):
print(list(graph.keys())[i],":",list(graph.values())[i])
bfs(visited,graph,'1')
Output:-
Result:-
Thus the python program for implementation graph representation and traversal algorithm is
executed successfully and output is verified.
13) Implementation of shortest path algorithm
Aim:
To write a python program for implementing shortest path algorithm.
Algorithm:
Step 1: start
Step 2: Initialize distance list as all infinities
Step 3: set distance for source to be 0
Step 4: Initialize list of visited notes
Step 5: mark starting node as -1
Step 6: use for loop
Step 7: declare dist[v] as dist[u] + d
Step 8: print dist[v]
Step 9: declare graph values
Step10: find length of the graph
Step11: print the sample of the graph
Step12: print source
Step13: print shortest distance
Step14: stop
Program:
Algorithm:-
Step 1:- start
Step 2:- declare a class graph
Step 3:-declare a constructer to give values for v and graph .
Step 4:-declare a member function printmst, minkey and primmst .
Step 5:- in main program declare g object .
Step 6:- given values for graphs.
Step 7:-stop
Program:-
import sys # Library for INT_MAX
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
# A utility function to print the constructed MST stored in parent[]
def printMST(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
def minKey(self, key, mstSet):
# Initialize min value
min = sys.maxsize
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
def primMST(self):
# Key values used to pick minimum weight edge in cut
key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V
parent[0] = -1
for cout in range(self.V):
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] >
self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST()
Output:-
>>>
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Result:-
Thus the python program was executed and the output was verified successfully.