Question: * * Please help with the code. no need to creat new class as I've already have one in previous section. Thanks! * * We
Please help with the code. no need to creat new class as I've already have one in previous section. Thanks!
We now wish to find the set of all nodes in the graph that belong to some cycle.
Example
Consider the example below: Zimagepng
Nodes lie on some cycle: example node lies on many cycles one such cycle being whereas the other nodes do not.
Note We do not treat undirected edges as cycles although in our data structure, when an undirected edge is represented as two "directed"
edges and it gives the impression that they are in a cycle of length
Complete the function findallnodesincycle that given a graph returns a python set of nodes in a cycle.
Hint Perform a DFS traversal and for each non triviaback edge discovered, use the DFS tree to figure out the nodes that must be on the cycle
corresponding to that back edge.
def findallnodesincycleg: & g is an UndirectedGraph class
setofnodes set
your code here
visited set
parent dict
def dfsnode parentnodeHone:
visited.addnode
parentnode parentnode
for neighbor in gadjlistnode:
if neighbor not in visitedr
dfsneighbor node
elif parentnode neighbor:
Add nodes to the set that are part of the cycle
cyclenode node
while cyclenode neighbor:
setofnodes.addcyclenode
Check if the cyclenode has a parent before accessing it
if cyclenode in parent:
cyclenode parentcyclenode
else:
break # Exit the loop if no parent is found
setofnodes.addneighbor
This line was causing the issue, adding node was creating a duplicate and Mone was being added to the set
setofnodes,addnode
for node in rangegn:
if node not in visited:
dfs node
return setofnodes
this is the example that we had for the problem.
g UndirectedGraph
gaddedge
gaddedge
gaddedge
gaddedge
gaddedge
g addedge
g addedge
gaddedge
s findallnodesincycleg
printfYour code returns set of nodes : s
let's also add the edge
gaddedge
s findallnodesincycleg
printfYour code returns set of nodes :
assert 'Fail: Set of nodes must be
printAll tests passedd: points!
Your code returns set of nodes: None
ow code returns set of nodes: None
AssertionBrror Traceback most recent call last
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
