Skip to main content

Overview

The Graph class is a factory that provides static methods to create different types of graph objects. It supports both adjacency matrix and adjacency list representations, with options for directed/undirected and weighted/unweighted graphs.

Static Methods

create

Create a graph object based on the specified parameters.
@staticmethod
create(graph_type: str, directed: bool = False, weighted: bool = False, vertices = None) -> object
graph_type
str
required
The type of graph representation:
  • 'adjacency_matrix' - Matrix-based representation
  • 'adjacency_list' - List-based representation
directed
bool
default:"False"
Whether the graph is directed
weighted
bool
default:"False"
Whether the graph edges have weights
vertices
list
default:"None"
List of vertex labels to initialize the graph with
return
object
A graph object of the appropriate type:
  • AdjacencyMatrixGraph (unweighted matrix)
  • AdjacencyMatrixWeightedGraph (weighted matrix)
  • AdjacencyListGraph (unweighted list)
  • AdjacencyListWeightedGraph (weighted list)
Raises: ValueError if an invalid graph type is provided
from dsa.graph import Graph

# Create unweighted, undirected adjacency matrix graph
g1 = Graph.create('adjacency_matrix')

# Create weighted, directed adjacency list graph
g2 = Graph.create('adjacency_list', directed=True, weighted=True)

# Create graph with initial vertices
g3 = Graph.create('adjacency_matrix', vertices=['A', 'B', 'C'])

create_adjacency_matrix

Create an adjacency matrix graph object.
@staticmethod
create_adjacency_matrix(directed: bool = False, weighted: bool = False, vertices = None) -> object
directed
bool
default:"False"
Whether the graph is directed
weighted
bool
default:"False"
Whether the graph edges have weights
vertices
list
default:"None"
List of vertex labels to initialize the graph with
return
object
An AdjacencyMatrixGraph or AdjacencyMatrixWeightedGraph instance
from dsa.graph import Graph

# Create unweighted adjacency matrix
g1 = Graph.create_adjacency_matrix()

# Create weighted, directed adjacency matrix
g2 = Graph.create_adjacency_matrix(directed=True, weighted=True)

# With initial vertices
g3 = Graph.create_adjacency_matrix(vertices=['A', 'B', 'C', 'D'])

create_adjacency_list

Create an adjacency list graph object.
@staticmethod
create_adjacency_list(directed: bool = False, weighted: bool = False, vertices = None) -> object
directed
bool
default:"False"
Whether the graph is directed
weighted
bool
default:"False"
Whether the graph edges have weights
vertices
list
default:"None"
List of vertex labels to initialize the graph with
return
object
An AdjacencyListGraph or AdjacencyListWeightedGraph instance
from dsa.graph import Graph

# Create unweighted adjacency list
g1 = Graph.create_adjacency_list()

# Create weighted, directed adjacency list
g2 = Graph.create_adjacency_list(directed=True, weighted=True)

# With initial vertices
g3 = Graph.create_adjacency_list(vertices=['X', 'Y', 'Z'])

from_dict

Create a graph from a dictionary representation.
@staticmethod
from_dict(data: dict, graph_type: str, directed: bool = False, weighted: bool = False) -> object
data
dict
required
Dictionary representation of the graph:
  • Unweighted: {vertex: [neighbor1, neighbor2, ...]}
  • Weighted: {vertex: {neighbor1: weight1, neighbor2: weight2, ...}}
graph_type
str
required
The type of graph: 'adjacency_matrix' or 'adjacency_list'
directed
bool
default:"False"
Whether the graph is directed
weighted
bool
default:"False"
Whether the graph is weighted
return
object
A graph instance of the specified type
Raises: ValueError if an invalid graph type is provided
from dsa.graph import Graph

# Create unweighted graph from dictionary
data_unweighted = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A', 'D'],
    'D': ['B', 'C']
}
g1 = Graph.from_dict(data_unweighted, 'adjacency_list')

# Create weighted graph from dictionary
data_weighted = {
    'A': {'B': 5, 'C': 3},
    'B': {'A': 5, 'D': 2},
    'C': {'A': 3, 'D': 7},
    'D': {'B': 2, 'C': 7}
}
g2 = Graph.from_dict(data_weighted, 'adjacency_matrix', weighted=True)

Complete Examples

from dsa.graph import Graph

# Undirected, unweighted adjacency matrix
g1 = Graph.create('adjacency_matrix')
g1.add_edge('A', 'B')
g1.add_edge('B', 'C')
print(g1.edges())  # [('A', 'B'), ('B', 'A'), ('B', 'C'), ('C', 'B')]

# Directed, weighted adjacency list
g2 = Graph.create('adjacency_list', directed=True, weighted=True)
g2.add_edge('X', 'Y', 10)
g2.add_edge('Y', 'Z', 20)
print(g2.edges())  # [('X', 'Y', 10), ('Y', 'Z', 20)]

# Using specific factory methods
g3 = Graph.create_adjacency_matrix(directed=True)
g3.add_edge('1', '2')
print(g3.has_edge('1', '2'))  # True
print(g3.has_edge('2', '1'))  # False (directed)

Graph Type Comparison

Adjacency Matrix

  • Best for: Dense graphs, frequent edge lookups, small graphs
  • Space Complexity: O(V²)
  • Edge Lookup: O(1)
  • Get All Edges: O(V²)
  • Add Vertex: O(V²) - requires matrix resize

Adjacency List

  • Best for: Sparse graphs, frequent vertex additions, large graphs
  • Space Complexity: O(V + E)
  • Edge Lookup: O(degree(V))
  • Get All Edges: O(V + E)
  • Add Vertex: O(1)

Directed Graphs

  • Edges have a direction (one-way)
  • Adding edge A→B does not create B→A
  • Use for: Web links, dependencies, one-way relationships

Undirected Graphs

  • Edges are bidirectional
  • Adding edge A-B automatically creates B-A
  • Use for: Social networks, road maps, mutual relationships

Weighted Graphs

  • Edges have associated weights/costs
  • Use for: Distance maps, cost optimization, network flow
  • Requires weight parameter when adding edges

Unweighted Graphs

  • Edges are either present or absent (boolean)
  • Use for: Simple connectivity, reachability problems
  • No weight parameter needed

Notes

  • All factory methods return concrete graph instances
  • Vertex labels must be strings
  • The factory automatically selects the appropriate graph class based on parameters
  • Invalid graph types raise a ValueError
  • Default behavior is undirected and unweighted graphs

Build docs developers (and LLMs) love