PYTHON
Model Graphs with Adjacency Lists in Python
Learn to represent graphs using an adjacency list pattern with dictionaries and sets in Python, perfect for managing relationships like social networks or web links.
class Graph:
def __init__(self, directed=False):
self.graph = {} # Dictionary: {node: set_of_neighbors}
self.directed = directed
def add_node(self, node):
if node not in self.graph:
self.graph[node] = set()
def add_edge(self, node1, node2):
self.add_node(node1) # Ensure nodes exist
self.add_node(node2)
self.graph[node1].add(node2)
if not self.directed:
self.graph[node2].add(node1) # For undirected graphs
def get_neighbors(self, node):
return self.graph.get(node, set())
def get_all_nodes(self):
return list(self.graph.keys())
def __str__(self):
return "\
".join([f"{node}: {sorted(list(neighbors))}" for node, neighbors in self.graph.items()])
# Example Usage: Undirected Graph (Social Network)
social_network = Graph(directed=False)
social_network.add_edge("Alice", "Bob")
social_network.add_edge("Bob", "Charlie")
social_network.add_edge("Alice", "David")
social_network.add_edge("Eve", "Bob")
print("--- Social Network (Undirected) ---")
print(social_network)
print(f"Alice's neighbors: {social_network.get_neighbors('Alice')}")
print(f"Bob's neighbors: {social_network.get_neighbors('Bob')}\
")
# Example Usage: Directed Graph (Web Links)
web_links = Graph(directed=True)
web_links.add_edge("Page A", "Page B")
web_links.add_edge("Page A", "Page C")
web_links.add_edge("Page B", "Page D")
web_links.add_edge("Page C", "Page B")
print("--- Web Links (Directed) ---")
print(web_links)
print(f"Pages linked from Page A: {web_links.get_neighbors('Page A')}")
print(f"Pages linked from Page B: {web_links.get_neighbors('Page B')}")
How it works: This snippet demonstrates how to represent a graph using an adjacency list in Python. An adjacency list is implemented here as a dictionary where each key is a node, and its corresponding value is a set of nodes it's connected to (its neighbors). Using a set for neighbors ensures uniqueness and efficient `add`/`remove` operations. The `Graph` class supports both directed and undirected graphs, making it versatile for modeling various relationships like social networks, web page links, or task dependencies.