Python graph data structure implementation

Darcy 172 Published: 10/30/2024

Python graph data structure implementation

Python is a popular programming language for creating various types of graphs. Here are some ways to implement a graph data structure using Python:

Adjacency Matrix Representation: In this method, we represent the graph as a matrix where the entry at position [i][j] represents whether there is an edge between node i and node j.
    class Graph:

def init(self):

self.adjMat = None

def addEdge(self, v1, v2):

if not self.adjMat:

numVertices = len(v1)

self.adjMat = [[0 for row in range(numVertices)]

for col in range(numVertices)]

self.adjMat[v1][v2] = 1

self.adjMat[v2][v1] = 1

def displayGraph(self):

if not self.adjMat:

return

numVertices = len(self.adjMat)

for i in range(numVertices):

print('Adjacency matrix:', end=' ')

for j in range(numVertices):

print(f' {self.adjMat[i][j]}', end=' ')

print()

Adjacency List Representation: In this method, we use a list of vertices where each vertex is associated with its adjacent nodes.
    class Graph:

def init(self):

self.adjList = {}

def addEdge(self, v1, v2):

if v1 not in self.adjList:

self.adjList[v1] = []

if v2 not in self.adjList:

self.adjList[v2] = []

self.adjList[v1].append(v2)

self.adjList[v2].append(v1)

def displayGraph(self):

for vertex, edges in self.adjList.items():

print(f'Vertex {vertex}: {edges}')

Edge List Representation: In this method, we store the graph as a list of edges where each edge is represented by its two vertices.
    class Graph:

def init(self):

self.edges = []

def addEdge(self, v1, v2):

self.edges.append((v1, v2))

def displayGraph(self):

for edge in self.edges:

print(f'Edge {edge[0]}-{edge[1]}')

Directed Graph: A directed graph is a type of graph where the edges are directed from one vertex to another. Here's how you can create a directed graph in Python.
    class DirectedGraph:

def init(self):

self.adjList = {}

def addEdge(self, v1, v2):

if v1 not in self.adjList:

self.adjList[v1] = []

self.adjList[v1].append(v2)

def displayGraph(self):

for vertex, edges in self.adjList.items():

print(f'Vertex {vertex}: {edges}')

Undirected Graph: An undirected graph is a type of graph where the edges are not directed. Here's how you can create an undirected graph in Python.
    class UndirectedGraph:

def init(self):

self.adjList = {}

def addEdge(self, v1, v2):

if v1 not in self.adjList:

self.adjList[v1] = []

if v2 not in self.adjList:

self.adjList[v2] = []

self.adjList[v1].append(v2)

self.adjList[v2].append(v1)

def displayGraph(self):

for vertex, edges in self.adjList.items():

print(f'Vertex {vertex}: {edges}')

Remember that these are just some basic implementations and there are many variations depending on your specific needs.

How do you represent a graph in Python?

Representing graphs in Python can be achieved using various libraries and data structures. Here are some popular methods:

Adjacency Matrix: You can store the adjacency matrix of a graph as a 2D list or numpy array, where adj_matrix[i][j] represents whether there is an edge between node i and node j.
    import numpy as np

from scipy.sparse import csr_matrix

Define nodes and edges

nodes = [0, 1, 2]

edges = [(0, 1), (1, 2)]

Create adjacency matrix

adj_matrix = np.zeros((len(nodes), len(nodes)), dtype=int)

for edge in edges:

i, j = edge

adj_matrix[i][j] = 1

Convert to scipy sparse matrix

adj_matrix = csr_matrix(adj_matrix)

print("Adjacency Matrix:")

print(adj_matrix.todense())

Edge List: Another way to represent a graph is as an edge list, where each element in the list represents an edge.
    nodes = [0, 1, 2]

edges = [(0, 1), (1, 2), (2, 0)]

print("Edges:")

for edge in edges:

print(edge)

Adjacency List: This representation is a combination of the adjacency matrix and edge list.
    nodes = [0, 1, 2]

graph = {i: [] for i in nodes}

for edge in edges:

i, j = edge

graph[i].append(j)

print("Adjacency List:")

for node, neighbors in graph.items():

print(f"Node {node} is connected to: {[str(n) for n in neighbors]}")

Graph Library: Python has several libraries that provide classes and functions for representing and manipulating graphs, such as: networkx: This library provides an easy-to-use interface for creating and manipulating networks, which are a type of graph.
        import networkx as nx
Create a directed graph

G = nx.DiGraph()

Add nodes and edges to the graph

G.add_node("A")

G.add_node("B")

G.add_edge("A", "B")

print("NetworkX Graph:")

print(G.edges())

igraph: This library is another popular option for working with graphs. Directed and Undirected: Depending on the type of graph you want to represent, it may be helpful to use directed or undirected edges in your representation.
    import igraph as ig
Create a directed graph

G = ig.Graph()

G.add_vertices(3)

G.add_edges([(0, 1), (1, 2)])

print("Directed Graph:")

for edge in G.get_edgelist():

print(edge)

Create an undirected graph

G = ig.Graph()

G.add_vertices(3)

G.add_edges([(0, 1), (1, 2)])

print("Undirected Graph:")

for edge in G.get_edgelist():

print(edge)

These are some of the ways you can represent a graph in Python. The choice depends on your specific use case and personal preference.

References:

NetworkX iGraph