Question: Basing on the code in the picture and class undirectedgraph, please help with 2 B code with error * * Your code computed MST: -
Basing on the code in the picture and class undirectedgraph, please help with B code with error Your code computed MST:
ValueError Traceback most recent call last
in # Iterate through the edges in mstedges, which are tuples of i j for edge in mstedges: i j edge # Unpack the edge into node indices i and j # Find the weight corresponding to the edge i j in the original graph g wij nextw for u v w in gedges if u i and v j or u j and v i
ValueError: too many values to unpack expected
Other preious code as FYI
class UndirectedGraph:
# n is the number of vertices
# we will label the vertices from to self.n
# We simply store the edges in a list.
def initself n:
assert n 'You are creating an empty graph disallowed'
self.n n
self.edges
self.vertexdata Noneselfn
def setvertexdataself j dat:
assert j self.n
self.vertexdataj dat
def getvertexdataself j:
assert j self.n
return self.vertexdataj
def addedgeself i j wij:
assert i self.n
assert j self.n
assert i j
# Make sure to add edge from i to j with weight wij
self.edges.appendi j wij
def sortedgesself:
# sort edges in ascending order of weights.
self.edges sortedselfedges, keylambda edgdata: edgdata
Question I need helpB:MST
def computemstg:
# Return a tuple of two items:
# List of edges i j that are part of the MST
# Sum of MST edge weights
d DisjointForestsgn
mstedges
mstweight
# Sort edges based on their weight
gsortedges
#Please only fix the below part
# Iterate over all edges, adding to MST if they don't form a cycle using unionfind
for i j wij in gedges:
if dfindi dfindj: # No cycle
dunioni j # Union the sets
mstedges.appendi j # Add edge to MST
mstweight wij # Add edge weight to MST weight
return mstedges, mstweight
Test implementation
g UndirectedGraph
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
mstedges, mstweight computemstg
printYour code computed MST:
# Iterate through the edges in mstedges, which are tuples of i j
for edge in mstedges:
i j edge # Unpack the edge into node indices i and j
# Find the weight corresponding to the edge i j in the original graph g
wij nextw for u v w in gedges if u i and v j or u j and v i
printft ij weight wij # Print the edge and its weight
printfTotal edge weight: mstweight
assert mstweight 'Optimal MST weight is expected to be
assert in gedges # Check if the edge exists in the original graph
assert in gedges
assert in gedges
assert in gedges
assert in gedges
assert in gedges
assert in gedges or in gedges # check if either edge is present
printAll tests passed: points!
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
