Graph Representations (Adjacency Lists)
Graphs model relationships between vertices and edges. In Python, an adjacency list is elegantly represented using a dictionary of lists: `graph = {node: [neighbors]}` 🕸️.
# Network Topology Graph:
graph = {
"Router_A": ["Switch_1", "Switch_2"],
"Switch_1": ["Server_Alpha"],
"Switch_2": ["Server_Beta"],
"Server_Alpha": [],
"Server_Beta": []
}
print(f"Router_A connects to: {graph['Router_A']} 🕸️")
# 9. Graph Representations (Adjacency Lists) Graphs model relationships between vertices and edges. In Python, an adjacency list is elegantly represented using a dictionary of lists: `graph = {node: [neighbors]}` 🕸️. ```python # Network Topology Graph: graph = { "Router_A": ["Switch_1", "Switch_2"], "Switch_1": ["Server_Alpha"], "Switch_2": ["Server_Beta"], "Server_Alpha": [], "Server_Beta": [] } print(f"Router_A connects to: {graph['Router_A']} 🕸️") ``` Whether modeling friend networks, dependency trees, or internet routing tables, dictionaries of lists provide $O(1)$ neighbor lookups! 🕸️ --- ### Question Why are adjacency lists preferred over $V \times V$ adjacency matrices for sparse real-world graphs? 🧠 - [ ] a. Adjacency lists only store actual existing edges, consuming $O(V + E)$ space instead of $O(V^2)$ 🕸️ - [ ] b. Adjacency matrices cannot store directed edges - [ ] c. Python dictionaries cannot store integers - [ ] d. Adjacency lists automatically run on GPUs --- ### Challenge Create graph `g = {'A': ['B', 'C'], 'B': ['D'], 'C': [], 'D': []}`. Print the number of outgoing neighbors from node `'A'` using `len(g['A'])`. 🎯 <details> <summary>Solution</summary> ```python g = {"A": ["B", "C"], "B": ["D"], "C": [], "D": []} print(len(g["A"])) ``` </details>