Skip to content

Commit ebb8472

Browse files
committed
Add doctests and type hints to Graph.dfs
1 parent a5a1f38 commit ebb8472

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

graphs/directed_and_undirected_weighted_graph.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,32 @@ def remove_pair(self, u, v) -> None:
355355
self.graph[v].remove(_)
356356

357357
# if no destination is meant the default value is -1
358-
def dfs(self, s=-2, d=-1):
358+
def dfs(self, s=-2, d=-1) -> None:
359+
"""
360+
Performs a depth-first search starting from node s.
361+
If destination d is given, stops when d is found
362+
363+
>>> g = Graph()
364+
>>> g.add_pair(1,2)
365+
>>> g.add_pair(2,3)
366+
>>> g.dfs(1)
367+
[1, 2, 3]
368+
>>> g.dfs(1,3)
369+
[1, 2, 3]
370+
>>> g.dfs(1,4) # 4 not in graph
371+
[1, 2, 3]
372+
>>> g.dfs(1,1) # start equals dest
373+
[]
374+
>>> g2 = Graph()
375+
>>> g2.add_pair(10,20)
376+
>>> g2.add_pair(20,30)
377+
>>> g2.dfs() # default start
378+
[10, 20, 30]
379+
>>> g2.add_pair(30,40)
380+
>>> g2.add_pair(40, 50)
381+
>>> g2.dfs(d=40) # checking if destination works properly
382+
[10, 20, 30, 40]
383+
"""
359384
if s == d:
360385
return []
361386
stack = []

0 commit comments

Comments
 (0)