Question: #Task 2 from graph import * G = Graph ( ) for i in [ ' A ' , ' B ' , ' C
#Task
from graph import
G Graph
for i in ABCDEFGHI:
GaddVertex Nodei
V Gvertices
#
#A B C D E F G H I
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
GaddBiEdge V V
# G is graph
# s is the node to start
def slowPrimG s:
# first, find the lightest edge leaving s
bestWt npinf
bestu None
for uwt in sgetOutNeighborsWithWeights:
if wt bestWt:
bestWt wt
bestu u
MST s bestu
verticesVisited sbestu
while lenverticesVisited lenGvertices: # danger! this will loop forever if the graph isn't connected...
# find the lightest edge xv so that x has been visited and v hasn't.
bestWt npinf
bestv None
bestx None
for x in verticesVisited:
for vwt in xgetOutNeighborsWithWeights:
if v in verticesVisited:
continue
if wt bestWt:
bestWt wt
bestv v
bestx x
MSTappendbestxbestv
verticesVisited.appendbestv
return MST
T slowPrimG Gvertices
for xy in T:
printxy
The above code works but is slow. I need it optimised.
This is the task question. Please leave detailed comments in the code and an explanation after to help me understand
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
