Complete the code to create a graph using an adjacency list.
graph = {}
graph['A'] = ['B', 'C']
graph['B'] = ['A', [1]]
graph['C'] = ['A']
print(graph)The adjacency list for node 'B' should include 'C' to represent the edge between B and C.
Complete the code to check if an edge exists between two nodes in a graph.
def has_edge(graph, node1, node2): return [1] in graph.get(node1, [])
To check if an edge exists from node1 to node2, we check if node2 is in the adjacency list of node1.
Fix the error in the code that tries to add an edge between two nodes in an undirected graph.
def add_edge(graph, node1, node2): if node1 not in graph: graph[node1] = [] if node2 not in graph: graph[node2] = [] graph[node1].append(node2) [1].append(node1)
To add an undirected edge, we add node1 to node2's adjacency list and node2 to node1's adjacency list. The second append should be to graph[node2].
Fill both blanks to create a function that counts the number of edges connected to a node in a graph.
def count_edges(graph, node): if node not in graph: return 0 return len(graph[1])
The adjacency list is accessed using square brackets with the node as the key: graph[node].
Fill all three blanks to create a function that returns all neighbors of a node that have a value greater than a threshold.
def neighbors_above_threshold(graph, node, threshold): return [neighbor for neighbor in graph[1] if neighbor [2] threshold] result = neighbors_above_threshold(graph, 'A', [3]) print(result)
The function accesses neighbors with graph[node], filters neighbors greater than threshold using >, and calls the function with threshold 5.
