Skip to content

Add to doctests #12790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add doctests and type hints to Graph.dfs
  • Loading branch information
tioBlachi committed Jun 9, 2025
commit ebb8472bd0e8a771d147e7538d3f7c4f95d5b3f3
27 changes: 26 additions & 1 deletion graphs/directed_and_undirected_weighted_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,32 @@ def remove_pair(self, u, v) -> None:
self.graph[v].remove(_)

# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
def dfs(self, s=-2, d=-1) -> None:
"""
Performs a depth-first search starting from node s.
If destination d is given, stops when d is found

>>> g = Graph()
>>> g.add_pair(1,2)
>>> g.add_pair(2,3)
>>> g.dfs(1)
[1, 2, 3]
>>> g.dfs(1,3)
[1, 2, 3]
>>> g.dfs(1,4) # 4 not in graph
[1, 2, 3]
>>> g.dfs(1,1) # start equals dest
[]
>>> g2 = Graph()
>>> g2.add_pair(10,20)
>>> g2.add_pair(20,30)
>>> g2.dfs() # default start
[10, 20, 30]
>>> g2.add_pair(30,40)
>>> g2.add_pair(40, 50)
>>> g2.dfs(d=40) # checking if destination works properly
[10, 20, 30, 40]
"""
if s == d:
return []
stack = []
Expand Down