Summary - Graph
- Algorithms course
- Intermediate
- Lesson 52/80
- 4 min
Print a small graph as an adjacency list in a mini task.
Summary - Graph
Graph: vertex + edge; cycles allowed. Directed/undirected, weighted/unweighted. Adjacency list O(V+E), matrix O(V^2).
Sparse graph → list, dense → matrix. Edge insertion is efficient in both.
Graphs underpin pathfinding, network analysis, dependency resolution. BFS and DFS work on this structure.
Practice Summary: count nodes
Write count_nodes(graph). Return the node count. Print 2 with print(count_nodes({'a': ['b'], 'b': ['a']})).
Starter code
def count_nodes(graph):
# Count nodesSample solution
def count_nodes(graph):
# Count nodes
return len(graph)
print(count_nodes({'a': ['b'], 'b': ['a']}))Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Summary - Graph: match the terms
| Term | Meaning |
|---|---|
Adjacency list |
O(V+E) |
Adjacency matrix |
O(V^2) |
Sparse |
List |
Dense |
Matrix |
2 Edge
The connection in a graph is called an ____.
The connection in a graph is called an edge.
Explanation: edge is right.
3 When is the adjacency matrix preferred?
- On a dense graph Correct answer
- On an empty graph
- Never
- On a sparse graph
Explanation: On a dense graph