Overview
TheGraph 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.The type of graph representation:
'adjacency_matrix'- Matrix-based representation'adjacency_list'- List-based representation
Whether the graph is directed
Whether the graph edges have weights
List of vertex labels to initialize the graph with
A graph object of the appropriate type:
AdjacencyMatrixGraph(unweighted matrix)AdjacencyMatrixWeightedGraph(weighted matrix)AdjacencyListGraph(unweighted list)AdjacencyListWeightedGraph(weighted list)
ValueError if an invalid graph type is provided
create_adjacency_matrix
Create an adjacency matrix graph object.Whether the graph is directed
Whether the graph edges have weights
List of vertex labels to initialize the graph with
An
AdjacencyMatrixGraph or AdjacencyMatrixWeightedGraph instancecreate_adjacency_list
Create an adjacency list graph object.Whether the graph is directed
Whether the graph edges have weights
List of vertex labels to initialize the graph with
An
AdjacencyListGraph or AdjacencyListWeightedGraph instancefrom_dict
Create a graph from a dictionary representation.Dictionary representation of the graph:
- Unweighted:
{vertex: [neighbor1, neighbor2, ...]} - Weighted:
{vertex: {neighbor1: weight1, neighbor2: weight2, ...}}
The type of graph:
'adjacency_matrix' or 'adjacency_list'Whether the graph is directed
Whether the graph is weighted
A graph instance of the specified type
ValueError if an invalid graph type is provided
Complete Examples
Graph Type Comparison
Adjacency Matrix vs Adjacency List
Adjacency Matrix vs Adjacency List
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 vs Undirected
Directed vs Undirected
Weighted vs Unweighted
Weighted vs Unweighted
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