Question: * * This is the third time asking for help, but still not working. Please kindly help * * [ 9 2 ] def find
This is the third time asking for help, but still not working. Please kindly help
def findallnodesincycleg:
setofnodes set # This will store nodes that are part of any cycle
visited set # To keep track of visited nodes
parent dict # TO keep track of the parent of each node in the DFS treedef dfsnode parentnodeNone:
visited.addnode # Mark node as visited
parentnode parentnode # Set the parent of the current nodefor neighbor in gadjlistnode:
if neighbor not in visited:dfsneighbor node
elif neighbor parentnode:cyclenode node
cyclepath cyclenodewhile cyclenode neighbor:
cyclenode parentcyclenode
cyclepath.appendcyclenode
setofnodes.updatecyclepath # Add all nodes in the cycle to the setfor node in rangegn:
if node not in visited:dfsnode
return setofnodes # Return the set of nodes that are in cycles
#this is the example that we had for the problem.
g UndirectedGraph
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
smathrm find all nodes in cycleg
printfYour code returns set of nodes: s
assert s 'Fail: Set of nodes must be gaddedge
s findallnodesincycleg
printfYour code returns set of nodes: s
assert s 'Fail: Set of nodes must be
printAll tests passedd: points!
KeyError Traceback most recent call last
ode
# Trace back using the parent nodes find all nodes the cycle
while ode neighbor:
ode parentode
ath.appendode
odes.updateath #Add all nodes the cycle the set
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
