|
3 | 3 | # Author: OMKAR PATHAK, Nwachukwu Chidiebere
|
4 | 4 |
|
5 | 5 | # Use a Python dictionary to construct the graph.
|
| 6 | +from __future__ import annotations |
6 | 7 |
|
7 | 8 | from pprint import pformat
|
| 9 | +from typing import Generic, TypeVar |
8 | 10 |
|
| 11 | +T = TypeVar("T") |
9 | 12 |
|
10 |
| -class GraphAdjacencyList: |
| 13 | + |
| 14 | +class GraphAdjacencyList(Generic[T]): |
11 | 15 | """
|
12 | 16 | Adjacency List type Graph Data Structure that accounts for directed and undirected
|
13 | 17 | Graphs. Initialize graph object indicating whether it's directed or undirected.
|
@@ -59,18 +63,27 @@ class GraphAdjacencyList:
|
59 | 63 | 5: [1, 4],
|
60 | 64 | 6: [2],
|
61 | 65 | 7: [2]}
|
| 66 | + >>> char_graph = GraphAdjacencyList(directed=False) |
| 67 | + >>> char_graph.add_edge('a', 'b') |
| 68 | + {'a': ['b'], 'b': ['a']} |
| 69 | + >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f') |
| 70 | + {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} |
| 71 | + >>> print(char_graph) |
| 72 | + {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} |
62 | 73 | """
|
63 | 74 |
|
64 |
| - def __init__(self, directed: bool = True): |
| 75 | + def __init__(self, directed: bool = True) -> None: |
65 | 76 | """
|
66 | 77 | Parameters:
|
67 | 78 | directed: (bool) Indicates if graph is directed or undirected. Default is True.
|
68 | 79 | """
|
69 | 80 |
|
70 |
| - self.adj_list = {} # dictionary of lists |
| 81 | + self.adj_list: dict[T, list[T]] = {} # dictionary of lists |
71 | 82 | self.directed = directed
|
72 | 83 |
|
73 |
| - def add_edge(self, source_vertex: int, destination_vertex: int) -> object: |
| 84 | + def add_edge( |
| 85 | + self, source_vertex: T, destination_vertex: T |
| 86 | + ) -> GraphAdjacencyList[T]: |
74 | 87 | """
|
75 | 88 | Connects vertices together. Creates and Edge from source vertex to destination
|
76 | 89 | vertex.
|
@@ -135,9 +148,3 @@ def add_edge(self, source_vertex: int, destination_vertex: int) -> object:
|
135 | 148 |
|
136 | 149 | def __repr__(self) -> str:
|
137 | 150 | return pformat(self.adj_list)
|
138 |
| - |
139 |
| - |
140 |
| -if __name__ == "__main__": |
141 |
| - import doctest |
142 |
| - |
143 |
| - doctest.testmod() |
|
0 commit comments