Complete the code to check if a graph has a cycle using DFS.
def dfs(node, visited, rec_stack): visited.add(node) rec_stack.add(node) for neighbor in graph[node]: if neighbor not in visited: if dfs(neighbor, visited, rec_stack): return True elif neighbor in [1]: return True rec_stack.remove(node) return False
The recursion stack rec_stack keeps track of nodes currently in the recursion path. If a neighbor is already in rec_stack, it means a cycle exists.
Complete the code to initialize the visited set before DFS traversal.
visited = set() for node in graph: if node not in [1]: if dfs(node, visited, set()): print("Cycle detected")
We check if a node is not in the visited set before starting DFS to avoid repeated work.
Fix the error in the cycle detection condition inside DFS.
if neighbor in visited and neighbor in [1]: return True
The cycle is detected if the neighbor is in the recursion stack, not just visited. So the condition should check rec_stack.
Fill both blanks to create a dictionary comprehension that maps each node to its neighbors count and filters nodes with more than 2 neighbors.
neighbor_counts = {node: len(graph[node]) for node in graph if len(graph[node]) [1] [2]The comprehension counts neighbors and filters nodes with more than 2 neighbors using > 2.
Fill all three blanks to create a dictionary comprehension that maps uppercase node names to their neighbor count, filtering nodes with at least 1 neighbor.
result = { [1]: len(graph[node]) for node in graph if len(graph[node]) [2] [3]The comprehension maps uppercase node names (node.upper()) to neighbor counts, filtering nodes with at least one neighbor (>= 1).