From c5003a2c462c7c775992ad9a733c360126702dd4 Mon Sep 17 00:00:00 2001 From: Hasanul Islam Date: Tue, 27 Jul 2021 14:09:17 +0600 Subject: [PATCH] Fix mypy errors at bfs_shortest_path algo (#4572) --- graphs/breadth_first_search_shortest_path.py | 28 +++++++++++--------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/graphs/breadth_first_search_shortest_path.py b/graphs/breadth_first_search_shortest_path.py index b43479d46..48f8ab1a4 100644 --- a/graphs/breadth_first_search_shortest_path.py +++ b/graphs/breadth_first_search_shortest_path.py @@ -3,6 +3,8 @@ from a given source node to a target node in an unweighted graph. """ from __future__ import annotations +from typing import Optional + graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], @@ -15,17 +17,19 @@ graph = { class Graph: - def __init__(self, graph: dict[str, str], source_vertex: str) -> None: - """Graph is implemented as dictionary of adjacency lists. Also, + def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: + """ + Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. """ self.graph = graph # mapping node to its parent in resulting breadth first tree - self.parent = {} + self.parent: dict[str, Optional[str]] = {} self.source_vertex = source_vertex def breath_first_search(self) -> None: - """This function is a helper for running breath first search on this graph. + """ + This function is a helper for running breath first search on this graph. >>> g = Graph(graph, "G") >>> g.breath_first_search() >>> g.parent @@ -44,7 +48,8 @@ class Graph: queue.append(adjacent_vertex) def shortest_path(self, target_vertex: str) -> str: - """This shortest path function returns a string, describing the result: + """ + This shortest path function returns a string, describing the result: 1.) No path is found. The string is a human readable message to indicate this. 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target @@ -64,17 +69,16 @@ class Graph: 'G' """ if target_vertex == self.source_vertex: - return f"{self.source_vertex}" - elif not self.parent.get(target_vertex): + return self.source_vertex + + target_vertex_parent = self.parent.get(target_vertex) + if target_vertex_parent is None: return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}" - else: - return self.shortest_path(self.parent[target_vertex]) + f"->{target_vertex}" + + return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" if __name__ == "__main__": - import doctest - - doctest.testmod() g = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D"))