Skip to content

Commit b64027b

Browse files
authored
Reduce side effect of shortest_path
For the sake of future testing and documentation -
1 parent 9f528c9 commit b64027b

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

graphs/breadth_first_search_shortest_path.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1+
"""Breath First Search (BFS) can be used when finding the shortest path
2+
from a given source node to a target node in an unweighted graph.
3+
"""
14
class Graph:
25
def __init__(self, graph, source_vertex):
3-
"""graph is implemented as dictionary of adjancency lists"""
6+
"""Graph is implemented as dictionary of adjancency lists. Also,
7+
Source vertex have to be defined upon initialization.
8+
"""
49
self.graph = graph
510
# mapping node to its parent in resulting breadth first tree
611
self.parent = {}
712
self.source_vertex = source_vertex
813

914
def breath_first_search(self):
10-
"""
15+
"""This function is a helper for running breath first search on this graph.
1116
"""
1217
visited = {self.source_vertex}
1318
self.parent[self.source_vertex] = None
@@ -21,14 +26,18 @@ def breath_first_search(self):
2126
self.parent[adjancent_vertex] = vertex
2227
queue.append(adjancent_vertex)
2328

24-
def print_shortest_path(self, target_vertex):
29+
def shortest_path(self, target_vertex):
30+
"""This shortest path function returns a string, describing the result:
31+
1.) No path is found. The string is a human readable message to indicate this.
32+
2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`,
33+
where v1 is the source vertex and vn is the target vertex, if it exists seperately.
34+
"""
2535
if target_vertex == self.source_vertex:
26-
print(self.source_vertex, end="")
36+
return f"{self.source_vertex}"
2737
elif target_vertex not in self.parent or not self.parent[target_vertex]:
28-
print(f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}")
38+
return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}"
2939
else:
30-
self.print_shortest_path(self.parent[target_vertex])
31-
print(f"->{target_vertex}", end="")
40+
return self.shortest_path(self.parent[target_vertex]) + f"->{target_vertex}"
3241

3342

3443
if __name__ == "__main__":
@@ -43,8 +52,6 @@ def print_shortest_path(self, target_vertex):
4352
}
4453
g = Graph(graph, "G")
4554
g.breath_first_search()
46-
g.print_shortest_path("D")
47-
print()
48-
g.print_shortest_path("G")
49-
print()
50-
g.print_shortest_path("Foo")
55+
print(g.shortest_path("D"))
56+
print(g.shortest_path("G"))
57+
print(g.shortest_path("Foo"))

0 commit comments

Comments
 (0)