Graphs#
- class data_structures.graphs.graphs.Graph[source]#
Bases:
objectUndirected weighted graph backed by an adjacency dictionary of Vertex objects.
- classmethod create_example_graph()[source]#
Example graph structure:
A / \ B --- C \ / D / \ E --- F
- classmethod build_graph(graph_definition: Dict[Any, List])[source]#
Create a Graph
- Parameters:
graph_definition – Graph definition
- Returns:
The Graph.
>>> str(Graph.create_example_graph()) '{"A": ["B", "C"], "B": ["C", "D"], "C": ["D"], "D": ["E", "F"], "E": ["F"], "F": []}'
- add_vertex(key) Vertex[source]#
Add a vertex for the given key if it does not already exist and return it.
- add_edge(key_vertex1, key_vertex2, weight=0)[source]#
Add a directed edge from key_vertex1 to key_vertex2 with an optional weight.
- breadth_first_search(node)[source]#
Algorithm used for tree traversal on graphs or tree data structures.
- Parameters:
node – Initial node.
- Returns:
List of visited nodes.
>>> Graph.create_example_graph().breadth_first_search("A") ['A', 'B', 'C', 'D', 'E', 'F']
- depth_first_search(node_id, visited: List | None = None)[source]#
Depth First Traversal Algorithm…
- Parameters:
node_id – Initial node.
visited – Set of visited nodes.
- Returns:
List of visited nodes.
>>> Graph.create_example_graph().depth_first_search("A") ['A', 'B', 'C', 'D', 'E', 'F']
- find_path(start, end, path: List | None = None)[source]#
Determine a path between two nodes…
- Parameters:
start – Start node.
end – End node.
path
- Returns:
The path.
>>> Graph.create_example_graph().find_path("A", "D") ["A", "B", "C", "D"]
- find_all_paths(start, end, path: List | None = None)[source]#
Determine all paths between two nodes…
- Parameters:
start – Start node.
end – End node.
path
- Returns:
The path.
>>> Graph.create_example_graph().find_all_paths("A", "D") [["A", "B", "C", "D"], ["A", "B", "D"], ["A", "C", "D"]]
- find_shortest_path(start, end)[source]#
Find the shortest path between two nodes…
- Parameters:
start – Start node.
end – End node.
- Returns:
Shortest path.
>>> Graph.create_example_graph().find_shortest_path("A", "F") ['A', 'B', 'D', 'F']
>>> Graph.create_example_graph().find_shortest_path("B", "E") ['B', 'D', 'E']