This function takes in a graph represented as an adjacency list, and returns whether or not the graph contains a cycle.
The candidate's solution is correct and demonstrates a good understanding of depth first search. However, the code could be more concise. For example, the has_cycle function could be written as follows: def has_cycle(g): visited = set() for node in g: if node not in visited: if dfs(node, visited, None): return 1 return 0 def dfs(node, visited, parent): visited.add(node) for neighbor in node: if neighbor not in visited: if dfs(neighbor, visited, node): return True elif neighbor != parent: return True return False
Evaluated at: 2022-11-27 08:16:06