Skip to content

Fix mypy errors at bfs_shortest_path algo #4572

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

Merged
Merged
Changes from all commits
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
28 changes: 16 additions & 12 deletions graphs/breadth_first_search_shortest_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"""
from __future__ import annotations

from typing import Optional

graph = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
Expand All @@ -15,17 +17,19 @@


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
Expand All @@ -44,7 +48,8 @@ def breath_first_search(self) -> None:
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
Expand All @@ -64,17 +69,16 @@ def shortest_path(self, target_vertex: str) -> str:
'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()
if __name__ == "__main__":
g = Graph(graph, "G")
g.breath_first_search()
print(g.shortest_path("D"))
Expand Down