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**
[92] def find_all_nodes_in_cycle(g):
set_of_nodes = 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 dfs(node, parent_node=None):
visited.add(node) # Mark node as visited
parent[node]= parent_node # Set the parent of the current nodefor neighbor in g.adj_list[node]:
if neighbor not in visited:dfs(neighbor, node)
elif neighbor != parent_node:cycle_node = node
cycle_path =[cycle_node]while cycle_node != neighbor:
cycle_node = parent[cycle_node]
cycle_path.append(cycle_node)
set_of_nodes.update(cycle_path) # Add all nodes in the cycle to the setfor node in range(g.n):
if node not in visited:dfs(node)
return set_of_nodes # Return the set of nodes that are in cycles
#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}=\mathrm{ find all nodes in cycle(g3)
print(f'Your code returns set of nodes: {s}')
assert s =={0,2,3,4}, 'Fail: Set of nodes must be {0,2,3,4}.'g3.add_edge(6,7)
s1= find_all_nodes_in_cycle(g3)
print(f'Your code returns set of nodes: {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!')
7
KeyError Traceback (most recent call last)
20,21,--22,>indfs(node,parentnode)
20, # Trace back using the parent nodes to find all nodes in the cycle
21, while cyclenode neighbor:
--22,cyclenode = parent[cyclenode]
23cyclepath.append(cyclenode)
24setofnodes.update(cyclepath) #Add all nodes in the cycle to the set
* * This is the third time asking for help, but

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!