Skip to content

Commit bc09ba9

Browse files
authored
Fix mypy errors at graph_list (TheAlgorithms#4557)
1 parent 4a2216b commit bc09ba9

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

graphs/graph_list.py

+17-10
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33
# Author: OMKAR PATHAK, Nwachukwu Chidiebere
44

55
# Use a Python dictionary to construct the graph.
6+
from __future__ import annotations
67

78
from pprint import pformat
9+
from typing import Generic, TypeVar
810

11+
T = TypeVar("T")
912

10-
class GraphAdjacencyList:
13+
14+
class GraphAdjacencyList(Generic[T]):
1115
"""
1216
Adjacency List type Graph Data Structure that accounts for directed and undirected
1317
Graphs. Initialize graph object indicating whether it's directed or undirected.
@@ -59,18 +63,27 @@ class GraphAdjacencyList:
5963
5: [1, 4],
6064
6: [2],
6165
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']}
6273
"""
6374

64-
def __init__(self, directed: bool = True):
75+
def __init__(self, directed: bool = True) -> None:
6576
"""
6677
Parameters:
6778
directed: (bool) Indicates if graph is directed or undirected. Default is True.
6879
"""
6980

70-
self.adj_list = {} # dictionary of lists
81+
self.adj_list: dict[T, list[T]] = {} # dictionary of lists
7182
self.directed = directed
7283

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]:
7487
"""
7588
Connects vertices together. Creates and Edge from source vertex to destination
7689
vertex.
@@ -135,9 +148,3 @@ def add_edge(self, source_vertex: int, destination_vertex: int) -> object:
135148

136149
def __repr__(self) -> str:
137150
return pformat(self.adj_list)
138-
139-
140-
if __name__ == "__main__":
141-
import doctest
142-
143-
doctest.testmod()

0 commit comments

Comments
 (0)