Complete the code to create a list of all vertices in the graph.
vertices = [[1] for edge in edges for vertex in edge]
The variable vertex represents each node in the edges, so we collect all vertices by iterating over edges and then over each vertex in those edges.
Complete the code to check if the graph is directed by comparing edges.
is_directed = any((v2, v1) not in edges for (v1, v2) in edges if v1 != v2 and [1])
We check only edges where the two vertices are different to avoid self-loops affecting the directed check.
Fix the error in the code to correctly add weighted edges to the graph dictionary.
graph = {}
for (u, v, w) in weighted_edges:
if u not in graph:
graph[u] = []
graph[u].[1]((v, w))We use append to add a tuple (v, w) to the adjacency list for vertex u.
Fill both blanks to create a dictionary of vertices with their degrees in an undirected graph.
degree = {vertex: 0 for vertex in vertices}
for (u, v) in edges:
degree[[1]] += 1
degree[[2]] += 1In an undirected graph, each edge increases the degree of both vertices u and v by 1.
Fill all three blanks to create a weighted adjacency dictionary from a list of edges.
weighted_graph = {}
for (src, dest, weight) in weighted_edges:
if [1] not in weighted_graph:
weighted_graph[[2]] = []
weighted_graph[src].append(([3], weight))We check if src is in the dictionary, add it if missing, then append the tuple (dest, weight) to the adjacency list for src.
