8
8
9
9
class DirectedGraph :
10
10
def __init__ (self ):
11
+ """
12
+ Initialize an empty directed graph.
13
+
14
+ Example:
15
+ >>> g = DirectedGraph()
16
+ >>> g.graph
17
+ {}
18
+ """
11
19
self .graph = {}
12
20
13
21
# adding vertices and edges
14
22
# adding the weight is optional
15
23
# handles repetition
16
24
def add_pair (self , u , v , w = 1 ):
25
+ """
26
+ Add a directed edge with an optional weight.
27
+
28
+ Args:
29
+ u: Starting node.
30
+ v: Destination node.
31
+ w: Weight (default is 1).
32
+
33
+ Example:
34
+ >>> g = DirectedGraph()
35
+ >>> g.add_pair(1, 2)
36
+ >>> g.graph
37
+ {1: [[1, 2]], 2: []}
38
+ >>> g.add_pair(2, 3, 5)
39
+ >>> g.graph
40
+ {1: [[1, 2]], 2: [[5, 3]], 3: []}
41
+ """
17
42
if self .graph .get (u ):
18
43
if self .graph [u ].count ([w , v ]) == 0 :
19
44
self .graph [u ].append ([w , v ])
@@ -27,6 +52,21 @@ def all_nodes(self):
27
52
28
53
# handles if the input does not exist
29
54
def remove_pair (self , u , v ):
55
+ """
56
+ Remove a directed edge from u to v.
57
+
58
+ Args:
59
+ u: Starting node.
60
+ v: Destination node.
61
+
62
+ Example:
63
+ >>> g = DirectedGraph()
64
+ >>> g.add_pair(1, 2)
65
+ >>> g.add_pair(1, 3)
66
+ >>> g.remove_pair(1, 2)
67
+ >>> g.graph
68
+ {1: [[1, 3]], 2: [], 3: []}
69
+ """
30
70
if self .graph .get (u ):
31
71
for _ in self .graph [u ]:
32
72
if _ [1 ] == v :
@@ -487,3 +527,8 @@ def bfs_time(self, s=-2):
487
527
self .bfs (s )
488
528
end = time ()
489
529
return end - begin
530
+
531
+
532
+ if __name__ == "__main__" :
533
+ import doctest
534
+ doctest .testmod ()
0 commit comments