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: Zimage-2.png
Nodes {0,2,3,4} lie on some cycle: example node 4 lies on many cycles one such cycle being 2-3-4. whereas the other nodes do not.
Note We do not treat undirected edges as cycles although in our data structure, when an undirected edge (i,j) is represented as two "directed"
edges (i,j) and (j,i), it gives the impression that they are in a cycle of length 2.
Complete the function find_all_nodes_in_cycle that given a graph returns a python set of nodes in a cycle.
Hint Perform a DFS traversal and for each non trivia/back edge discovered, use the DFS tree to figure out the nodes that must be on the cycle
corresponding to that back edge.
def find_all_nodes_in_cycle(g): & g is an UndirectedGraph class
set_of_nodes = set()
your code here
visited = set()
parent = dict()
def dfs(node, parent_node=Hone):
visited.add(node)
parent[node]= parent_node
for neighbor in g.adj_list[node]:
if neighbor not in visitedr
dfs(neighbor, node)
elif parent_node 1= neighbor:
Add nodes to the set that are part of the cycle
cycle_node = node
while cycle_node 1= neighbor:
set_of_nodes.add(cycle_node)
Check if the cycle_node has a parent before accessing it
if cycle_node in parent:
cycle_node = parent[cycle_node]
else:
break # Exit the loop if no parent is found
set_of_nodes.add(neighbor)
This line was causing the issue, adding node was creating a duplicate and Mone was being added to the set
*set_of_nodes,add(node)
for node in range(g.n):
if node not in visited:
dfs (node)
return set_of_nodes
[77] this is the example that we had for the problem.
g3= UndirectedGraph(8)
g3.add_edge (0,1)
g3.add_edge (0,2)
g3.add_edge (0,4)
g3.add_edge (2,3)
g3.add_edge (2,4)
g3. add_edge (3,4)
g3. add_edge (5,6)
g3.add_edge (5,7)
s = find_all_nodes_in_cycle(g3)
print(f'Your code returns set of nodes : (s)')
let's also add the edge 6,7
g3.add_edge (6,7)
s 1- find_all_nodes_in_cycle(g3)
print(f'Your code returns set of nodes {:f(s1}')
assert s1={0,2,3,4,5,6,7}, 'Fail: Set of nodes must be {0,2,3,4,5,6,7}.'
print('All tests passedd: 10 points!')
\ Your code returns set of nodes: {0,2,3,4, None}
\ow code returns set of nodes: {0,2,3,4, None }
AssertionBrror Traceback (most recent call last)
* * Please help with the code. no need to creat

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!