Data Structure
Data Structure
Aim:
To Implement simple ADTs as Python classes using Stack,Queue,List using python.
Algorithm:
1. Create a Stack [],Queue[],List[]with MAX size as your wish.
2. Write function for all the basic operations of stack,Queue,List-PUSH(),POP()and
DISPLAY(),append(),Extend().
3. Close the program
Coding:
Stack:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initialstack')
print(stack)
print('\nElementspopedfromstack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStackafterelementsarepoped:') print(stack)
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initialqueue")
print(queue)
print("\nElementsdequeuedfromqueue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueueafterremovingelements")
print(queue)
1
List:
List=[1,2,3,4]
print("InitialList:")
print(List)
List.extend([8,'Geeks','Always'])
print("\nListafterperformingExtendOperation:")
print(List)
Output:
Stack:
Initialstack
['a', 'b', 'c']
Elementspopedfromstack: c
b
a
Stackafterelementsarepoped: []
Queue:
['a','b','c']
Elementsdequeuedfromqueue a
b
c
Queueafterremovingelements
[]
List:
InitialList:
[1,2,3,4]
ListafterperformingExtendOperation: [1,
2, 3, 4, 8, 'Geeks', 'Always']
Result:
Thus the Implementation of simple ADTs as Python classes was executed successfully.
2
Ex.No:2 Implement recursive algorithms in Python
Aim:
To Implement are cursive algorithms in Python using Fibonacci Series
Algorithm:
Step1:Input the 'n' value until which the Fibonacci series has to be generated
Step3:while(count<=n)
Step4:print sum
Step6:swap a and b
Step7:sum=a+b
Step9:Endthealgorithm
Step 10:Else
Coding:
No=10
num1, num2 =0, 1
count =
0ifNo<=0:
print("InvalidNumber")
elif No == 1:
print("Fibonaccisequenceforlimitof",No,":")
print(num1)
else:
print("Fibonaccisequence:")
while count < No:
print(num1)
nth=num1+num2 num1
= num2
3
num2=nth
count += 1
Output:
Fibonaccisequence:
0
1
1
2
3
5
8
13
21
34
Result:
Thus the Implementation of recursive algorithms in Python using Fibonacci series
was executed successfully.
4
Ex.No:3 Implement List ADT using Python arrays
Aim:
To Implement List ADT using Python arrays
Algorithm
1. Using define function intialise the list
2. While loop to declare the elements until the condition is satisfied.
3. Using convert arr function to convert the elements to an array
4. Stop the program
Coding:
classnode:
definit(self,data):self.da
ta=dataself.next=None
defadd(data):nn=node(
0)nn.data=datann.
next=Nonereturnnn
defprintarray(a,n):i=
0
while(i<n):
print(a[i],end="")i=i+
1
deffindlength(head):c
ur=head
count=0while(cur!
=None):
count=count+1
cur=cur.nextretur
ncount
defconvertarr(head):len=findl
ength(head)arr=[]
5
index=0c
ur=head
while(cur!=None):arr.append
(cur.data)cur=cur.next
printarray(arr,len)
head=node(0)head=add(6)
head.next=add(4)head.next.next
=add(3)head.next.next.next=add
(4)convertarr(head)
Output:
[6,4,3,4]
[6434]
Result:
Thus the implementation of List in arrays was executed successfully.
6
Ex.NO:4 Linked list implementations of List
Aim:
To Implement the Linked list implementations of List using python.
Algorithm:
1. Create a list[] with MAX size as your wish.
2. Write function for all the basic operations of list - create(),insert(),deletion(), display().
3. Using append() to extend the elements,removal() to delete the elements
4. Close the program.
Coding:
List=[1,2,3,4]
print("InitialList:")
print(List)
List.extend([8,'Geeks','Always'])
print("\nListafterperformingExtendOperation:")
print(List)
List = []
print("BlankList:")
print(List)
List=[10,20, 14]
print("\nListofnumbers:")
print(List)
List=["Geeks","For","Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Addingtheelements:
List=[1,2,3,4]
print("Initial List: ")
print(List)
List.insert(3, 12)
List.insert(0,'Geeks')
print("\nListafterperformingInsertOperation:")
print(List)
List=[1, 2,3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("IntialList:")
print(List)
7
List.remove(5)
List.remove(6)
print("\nListafterRemovaloftwoelements:")
print(List)
foriinrange(1,5):
List.remove(i)
print("\nListafterRemovingarangeofelements:")
print(List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-DimensionalList:")
print(List)
Output:
InitialblankList:
[]
ListafterAdditionofThree elements:
[1,2,4]
ListafterAdditionofelementsfrom1-3:
[1,2,4,1,2,3]
>>>
=====================RESTART:Z:/Newfolder/queue1.py
=====================
InitialList:
[1,2,3,4]
ListafterperformingInsertOperation:
['Geeks',1,2,3,12,4]
>>>
=====================RESTART:Z:/Newfolder/queue1.py
=====================
IntialList:
[1,2,3,4,5,6,7,8,9,10,11,12]
ListafterRemovaloftwo elements:
[1,2,3,4,7,8,9,10,11,12]
List after Removing a range of elements:
[7,8,9,10,11,12]
Result:
Thus the list was created,inserted,removed and extend the element was executed successfully.
8
Ex.No:5 Implementation of Stack Queue ADT
Aim:
To Implementation of Stack and Queue ADTs
Algorithm:
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initialqueue")
print(queue)
print("\nElementsdequeuedfromqueue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueueafterremovingelements")
print(queue)
Output:
Initialstack
['a', 'b', 'c']
9
Elements poped from stack:
c
b
a
Stackafterelementsarepoped: []
Result:
Thus the program was executed successfully
10
Ex.No:6a Application of List
Aim:
To implement list application using Polynomial Addition in python
Algorithm:
1. Using the define function intial elements will be declared.
2. For loop gives the output of sum of the elements
3. Print [poly] statement have the sum of two polynomial elements.
4. Close the program
Coding:
Def add(A,B,m,n):
size=max(m, n);
sum=[0foriinrange(size)] for
i in range(0, m, 1):
sum[i] = A[i]
foriinrange(n):
sum[i]+=B[i]
return sum
defprintPoly(poly,n):
for i in range(n):
print(poly[i],end="") if
(i != 0):
print("x^",i,end="") if
(i != n - 1):
print("+",end="")
ifname == 'main':
A=[5, 0,10, 6]
B=[1, 2, 4]
m= len(A)
11
n = len(B)
print("Firstpolynomialis")
printPoly(A, m)
print("\n", end = "")
print("Secondpolynomialis")
printPoly(B, n)
print("\n",end="")
sum = add(A, B, m, n)size
= max(m, n)
print("sumpolynomialis")
printPoly(sum, size)
Output:
First polynomialis
5+0x^1+10x^2+6x^3 Second
polynomial is
1+2x^1 +4x^2
Sum polynomialis
6+2x^1+14x^2 +6x^3
Result:
Thus the program was executed successfully.
12
Ex.No:6b Application of Stack
Aim:
To implement the conversion of infix to postfix in stack
Algorithm:
1. Read the given expression
2. Check if empty or not, the stack will insert the elements.
3. Using push(),pop() to insert the element or remove the element.
4. Check the operator based on the precedence the expression will be evaluated
5. Close the program
Coding:
Class Conversion:
self. array = []
self. output=[]
self. precedence={'+':1,'-':1,'*':2,'/':2,'^':3}
def is Empty(self):
return True if self. top==-1elseFalse
defpeek(self):
returnself.array[-1]
defpop(self):
ifnotself.isEmpty():
self.top -= 1
returnself.array.pop()
else:
return"$"
defisOperand(self,ch):
return ch.isalpha()
defnotGreater(self,i):
try:
13
a=self.precedence[i]
b=self.precedence[self.peek()]
returnTrueifa<=belse False
exceptKeyError:
return False
definfixToPostfix(self,exp):
foriinexp:
if self.isOperand(i):
self.output.append(i)
elifi==')':
while((notself.isEmpty())and
self.peek()!='('): a
= self.pop()
self.output.append(a)
if(notself.isEmpty()andself.peek()!='('):
return -1
else:
self.pop()
else:
while(notself.isEmpty()andself.notGreater(i)):
self.output.append(self.pop())
self.push(i)
exp="a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)
Output:
abcd^e-fgh*+^*+i-
Result:
Thus the conversion can be successfully executed
14
Ex.No:6c Application of Queue
Aim:
To implement the application of queue using FCFS CPU Scheduling
Algorithm:
1. Input the number of processes required to be scheduled using FCFS, burst time for
each process and its arrival time.
2. Calculate the Finish Time, Turn Around Time and Waiting Time for each process which
in turn help to calculate Average Waiting Time and Average Turn Around Time require
by CPU to schedule given set of process using FCFS.
3. Process with less arrival time comes first and gets scheduled first by the CPU.
4. Calculate the Average Waiting Time and Average Turn Around Time.
5. Stop the program
Coding:
Def find Waiting Time (processes, n, bt, wt):
wt[0]=0
for I in range(1,n):
wt[i]=bt [i-1] +wt[i-1]
calculating turnaround
#time by adding bt [i]+wt[i]
for i in
range(n):tat[i]=bt[]
+wt[i]
wt = [0] * n
tat=[0]*n
total_wt=0
15
total tat = 0
for I in range(n):
total_wt=total_wt+wt[i]
total_tat= total_tat+tat[i]
print(""+str(i+1)+"\t\t"+ str(bt[i])+"\t"
str(wt[i])+"\t\t"+ str(tat[i]))
if name =="main":
processes = [ 1, 2, 3]
n = len(processes)
burst_time=[10,5,8]
find avg Time(processes, n, burst_time)
Output:
Processes Burst time Waiting time Turn around time
1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time=8.33333
Average turn around time=16
Result:
Thus the FCFS CPU Scheduling was Executed Successfully
16
Ex.No:7A Implementation of searching algorithms
Aim:
To implement searching using Linear and Binary Search algorithm using python
Algorithm:
Linear Search:
1. Read the search element from the user
2. Compare, the search element with the first element in the list
.3.Ifbothare matching, then display "Given element found!!!" and terminate the function
4. If both are not matching, then compare search element with the next element in the list.
5. Repeat steps 3 and 4 until the search element is compared with the last element in the list.
6. If the last element in the list is also doesn't match, then display "Element not found!!!"and
terminate the function.
Binary search:
1. Read the search element from the user
2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!"and terminate the function
5. If both are not matching, then check whether the search element is smaller or larger
than middle element
.6.If the search element is smaller than middle element, then repeat steps2,3,4and5forthe left
sub list of the middle element.
7. If the search element is larger than middle element, then repeat steps2,3,4and5for the right
sub list of the middle element.
8. Repeat the same process until we find the search element in the list or until sub list
contains only one element.
9. If that element also doesn't match with the search element, then display "Element not found in
the list!!!" and terminate the function.
17
return-1
arr=[10,20,30,40,50,60,70,80,90,100]
key=40
result=BinarySearch(arr,0,len(arr)-1,key) if
result != -1:
print(key,"Foundatindex",str(result))
else:
print(key,"not Found")
Result:
Thus the implementation of searching using Linear and Binary Search using python was
executed successfully
18
Ex.No:7B Implementation of Sorting Algorithm
Aim:
To Implement sorting algorithm using Quick Sortand Insertion Sort algorithm using python
Algorithm:
Quick Sort:
1. Find a “pivot” item in the array. This item is the basis for comparison for a single
round.
2. Start a pointer (the left pointer) at the first item in the array.
3. Start a pointer (the right pointer) at the last item in the array.
4. While the value at the left pointer in the array is less than the pivot value, move the
left pointer to the right (add1).Continue until the value at the left pointer is greater
than or equal to the pivot value.
5. While the value at the right pointer in the array is greater than the pivot value, move
the right pointer to the left(subtract1).Continue until the value at the right pointer is
less than or equal to the pivot value.
6. If the left pointer is less than or equal to the right pointer, then swap the values at
these locations in the array.
7. Move the left pointer to the right by one and the right pointer to the left by one.
Insertion Sort:
ifarr[j]<=pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high]=arr[high],arr[i+1]
return ( i+1 )
defquickSort(arr,low,high):
if low < high:
19
pi=partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
arr= [2,5,3,8,6,5,4,7]
n = len(arr)
quickSort(arr,0,n-1)
print("Sortedarrayis:")
for i in range(n):
print(arr[i],end="")
Output:
Quick Sorted array is:
23455678
Insertion sorted array is:
a
i
l
o
r
t
t
u
Result:
Thus the implementation of searching Quick and Insertion Sort algorithm using python
was executed successfully
20
Ex.No:8 Implementation of Hash tables
Aim:
To Implement the Hash tables using python
Algorithm:
1. Create a structure, data (hash table item)with key and value as data.
2. For loops to define the range with in the set of
elements.
3. 3.hash function(key) for the size of capacity
4. Using insert(),removal() data to be presented or removed.
5. Stop the program
Coding:
hashTable=[[],]*10 def
checkPrime(n):
ifn==1orn==0: return 0
foriinrange(2,n//2): if
n % i == 0:
return0
return1
defgetPrime(n):
ifn%2==0:
n =n +1
whilenotcheckPrime(n):
n += 2
returnn
def hashFunction(key):
capacity=getPrime(10)
return key % capacity
def insertData(key, data):
index=hashFunction(key)
hashTable[index]=[key,data]
def removeData(key):
index=hashFunction(key)
hashTable[index] = 0
insertData(123, "apple")
insertData(432,"mango")
insertData(213,"banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
21
print(hashTable)
Output:
[[],[],[123,'apple'],[432,'mango'],[213,'banana'],[654,'guava'],[],[],[],[]]
[[],[],0,[432,'mango'],[213,'banana'],[654,'guava'],[],[],[], []]
Result:
Thus the Implementation of hashing was executed successfully
22
Ex.No:9a Tree representation
Aim:
To implement tree representation in binary tree format
Algorithm:
1. Create a binary tree.
2. Intially all the left and right vertex are none, then declare the values using insert() function.
3. If data>right element place the element in right
4. If data<left element place the element in left
5. Print the tree
6. Stop the program
Coding:
Class Node:
definit(self,data): self.left
= None self.right =
None self.data = data
definsert(self,data):
if self.data:
ifdata<self.data:
if self.left is None:
self.left=Node(data)
else:
self.left.insert(data)eli
f data > self.data:
if self.right is None:
self.right=Node(data)
else:
self.right.insert(data)
else:
self.data=data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data),
if self.right:
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
23
root.PrintTree()
Output:
3
6
12
14
Result:
Thus the binary tree was successfully created
24
Ex.No:9b Tree Traversal Algorithms
Aim:
To Implement traversal using Inorder, Preorder, Postorder techniques.
Algorithm:
In order(tree)
1. Traverse the left subtree,i.e.,callInorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree,i.e.,callInorder(right-subtree)
Pre order(tree)
1. Visit the root.
2. Traverse the left subtree,i.e.,call Preorder(left-subtree)
3. Traverse the right subtree,i.e.,call Preorder(right-subtree)
Post order(tree)
1. Traverse the left subtree,i.e.,call Post order(left-subtree)
2. Traverse the right subtree,i.e.,call Postorder(right-subtree)
4. Visittheroot
Coding:
classNode:
definit(self,key): self.left
= None self.right =
None self.val = key
defprintInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
defprintPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val),
defprintPreorder(root):
if root:
print(root.val),
printPreorder(root.left)
printPreorder(root.right)
25
root = Node(1)root.left
= Node(2)
root.right = Node(3)
root.left.left=Node(4)
root.left.right= Node(5)
print("\nPreordertraversalofbinarytreeis")
printPreorder(root)
print("\nInordertraversalofbinarytreeis")
printInorder(root)
print("\nPostordertraversalofbinarytreeis")
printPostorder(root)
Output:
Preordertraversalofbinarytreeis 1
2
4
5
3
Inordertraversalofbinarytreeis 4
2
5
1
3
Postordertraversalofbinarytreeis 4
5
2
3
1
Result:
Thus the Implementation of traversal using Inorder, Preorder, Postorder techniques was
executed successfully
26
Ex.No:10 Implementation of Binary Search Trees
Aim:
To implement the Binary Search Trees using python
Algorithm:
Step2-Compare the search element with the value of root node in the tree.
Step3-If both are matched, then display "Given node is found!!!" and terminate the function
Step4-If both are not matched, then check whether search element is smaller or larger than that
node value.
Step5-If search element is smaller, then continue the search process in left subtree.
Step6-If search element is larger, then continue the search process in right subtree.
Step7-Repeat the same until we find the exact element or until the search element is compared
with the leaf node
Step8-If we reach to then odehaving the value equal to the search value then display "Element is
found" and terminate the function.
Coding:
classNode:
definit(self,data): self.left
= None self.right =
None self.data = data
definsert(self,data):
if self.data:
ifdata<self.data:
if self.left is None:
self.left=Node(data)
else:
self.left.insert(data)eli
f data > self.data:
if self.right is None:
self.right=Node(data)
else:
27
self.right.insert(data)
else:
self.data=data
deffindval(self,lkpval):
if lkpval < self.data:
ifself.leftis None:
returnstr(lkpval)+"NotFound"
return self.left.findval(lkpval)
elif lkpval > self.data:
ifself.rightisNone:
returnstr(lkpval)+"NotFound"
return self.right.findval(lkpval)
else:
print(str(self.data)+'isfound')
defPrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
Output:
7NotFound
14is found
Result:
Thus the Implementation of Binary Search Trees using python was executed successfully.
28
Ex.NO:11 Implementation of Heaps
Aim:
To Implement the Heap algorithm using python
Algorithm:
1. Insert the heap function in the list
2. Using heap push(),heap pop(),heap if y()to insert, delete, display the elements.
3. Stop the program
Coding:
import heapq
H=[21,1,45,78,3,5]
heapq.heapify(H)
print(H)
heapq.heappush(H,8)
print(H)
heapq.heappop(H)
print(H)
Output:
1, 3, 5, 78, 21, 45
[1,3,5,78,21,45,8]
[3,8,5,78,21,45]
Result:
29
Ex.No:12a Graph representation
Aim:
To implement graph representation python
Algorithm:
1. Start The Program
2. Define a class Graph
3. Defin the –init—method to initiate the graph dictionary gdict
4. i) Define method getVertices(self)
ii) Return a list of all the keys from the graph dictionary (i.e., vertices)
5.Create a graph using a sample dictionary graph_elements
6. create an object g of class Graph
7. Call g.getVertices() to print all vetices
8. Stop
30
if {nxtvrtx, vrtx} not in edgename:
edgename.append({vrtx,nxtvrtx})
return edgename
graph_elements={"a":["b","c"],
"b":["a","d"],
"c":["a","d"],
"d":["e"],
"e":["d"]
}
g=graph(graph_elements)
print(g.edges())
Output:
DISPLAYINGVERTICES
['a', 'b', 'c', 'd', 'e']
DISPLAYING EDGES
[{'a','b'},{'a','c'},{'d','b'},{'c','d'},{'d','e'}]
Result:
Thus the implementation of graphs was executed successfully.
31
Ex.No:12b Graph Traversal Algorithms
Aim:
To Implement using BFS, DFS can be traversed.
Algorithm:
DFS:
Step2-Select any vertex as starting point for traversal.Visit that vertex and push it on to the
Stack.
Step3-Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack
and push it on to the stack.
Step4-Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top of
the stack.
Step5-When there is no new vertex to visit then use backtracking and pop one vertex from the
stack.
Step7-When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph
BFS:
Step2-Select any vertex as startingpoint for traversal.Visit that vertex and insert it into the
Queue.
Step3-Visit all then on-visited adjacent vertices of the vertex which is at front of the Queue and
insert them into the Queue.
Step4-When there is no new vertex to be visited from the vertex which is at front of the Queue
then delete that vertex.
Step6-When queue becomes empty,then produce final spanning tree by removing unused edges
from the graph
32
Coding:
BFS
import collections
defbfs(graph,root):
visited,queue=set(),collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
print(str(vertex) + "", end="")
forneighbouringraph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
ifname == 'main':
graph={0: [1, 2], 1:[2], 2: [3], 3: [1, 2]}
print("FollowingisBreadthFirstTraversal:")
bfs(graph, 0)
Output:
FollowingisBreadthFirstTraversal:
0123
DFSCoding:
import sys
defret_graph():
return {
'A':{'B':5.5,'C':2,'D':6},
'B':{'A':5.5,'E':3},
'C':{'A':2,'F':2.5},
'D':{'A':6,'F':1.5},
'E':{'B':3,'J':7},
'F':{'C':2.5,'D':1.5,'K':1.5,'G':3.5}, 'G':
{'F':3.5, 'I':4},
'H':{'J':2},
'I':{'G':4,'J':4},
'J':{'H':2,'I':4},
'K': {'F':1.5}
}
start = 'A'
dest = 'J'
visited=[]
33
stack=[]
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr=stack.pop()
path.append(curr)
forneighingraph[curr]:
ifneighnotinvisited:
visited.append(neigh)
stack.append(neigh)if
neigh == dest :
print("FOUND:",neigh)
print(path)
sys.exit(0)
print("Not found")
print(path)
Output:
FOUND:J
['A','D','F','G','I']
Result:
Thus the implementation of using BFS,DFS graph can be traversed.
34
Ex.No:13 Implementation of single source shortest path algorithm
Aim:
To Implement single source shortest path algorithm using BellmanFord Algorithm
Algorithm:
1) This step initializes distances from source to all vertices as infinite and distance to source
itself as 0.Create an array list[]of size|V|with all values as infinite except dist[src]where src is
source vertex.
2) This step calculates shortest distances.Do following|V|-1times where|V|is the number of
vertices in given graph.
a)Do following for each edgeu-v
Ifdist[v]>dist[u]+weight of edge uv,then updated ist[v]
dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle in graph.Do following for each edge u-v
If dist[v]>dist[u]+weight of edge uv,then “Graph contains negative weight cycle”
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative
weight cycle.If we iterate through all edges one more time and get a shorter path for any vertex,
then there is a negative weight cycle
Coding:
fromsysimport maxsize
defBellmanFord(graph,V,E,src):
dis = [maxsize] * V
dis[src]=0
foriinrange(V-1): for
j in range(E):
ifdis[graph[j][0]]+\
graph[j][2]<dis[graph[j][1]]:
dis[graph[j][1]]=dis[graph[j][0]]+\
graph[j][2]
for i in range(E):
x =graph[i][0]
y = graph[i][1]
weight=graph[i][2]
ifdis[x]!=maxsizeanddis[x]+\ weight <
dis[y]:
print("Graphcontainsnegativeweightcycle")
print("Vertex Distance from Source")
for i in range(V):
print("%d\t\t%d"%(i,dis[i]))
35
if name =="main":
V =5 # Number of vertices in graph
E = 8 # Number of edges in graph
graph=[[0,1,-1],[0,2,4],[1,2,3],
[1,3,2],[1,4,2],[3,2,5],
[3,1,1],[4,3,-3]]
BellmanFord(graph,V,E,0)
Output:
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
Result:
Thus the Implementation of single source shortest path algorithm was successfully executed.
36
Ex.No:14 Implementation of minimum spanning tree algorithms
Aim:
To implement the minimum spanning tree algorithms using Kruskal Algorithm
Algorithm:
1. Label each vertex
2. List the edges in non-decreasing order of weight.
3. Start with the smallest weighted and beginning growing the minimum weighted spanning tree
from this edge.
4. Add the next available edge that does not form a cycle to the construction of the minimum
weighted spanning tree.If the addition of then ext least weighted edge forms acycle,do not use
it.
5. Continue with step 4 until you have a spanning tree.
Coding:
Class Graph:
definit(self,vertices): self.V
= vertices self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u,v,w])
deffind(self,parent,i):
returnself.find(parent,parent[i])
defapply_union(self,parent,rank,x,y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
ifrank[xroot]<rank[yroot]:
parent[xroot]=yroot
elifrank[xroot]>rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot]=xroot
rank[xroot] += 1
defkruskal_algo(self):
result = []
i, e =0, 0
self.graph=sorted(self.graph,key=lambdaitem:item[2]) parent
= []
rank=[]
fornodeinrange(self.V):
parent.append(node)
rank.append(0)
37
whilee<self.V-1:
u,v,w=self.graph[i] i
=i+1
x=self.find(parent,u)
y=self.find(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("%d-%d:%d"%(u,v,weight)) g =
Graph(6)
g.add_edge(0,1,4)
g.add_edge(0,2,4)
g.add_edge(1,2, 2)
g.add_edge(1,0,4)
g.add_edge(2,0,4)
g.add_edge(2,1,2)
g.add_edge(2,3,3)
g.add_edge(2,5,2)
g.add_edge(2,4,4)
g.add_edge(3,2,3)
g.add_edge(3,4,3)
g.add_edge(4,2,4)
g.add_edge(4,3,3)
g.add_edge(5,2,2)
g.add_edge(5,4,3)g.
kruskal_algo()
Output:
1 -2: 2
2 -5: 2
2 -3: 3
3 -4: 3
0 -1: 4
Result:
Thus the program was executed successfully
38