From 977511b3a3711ad9067cc1e8478c696e9f5f157d Mon Sep 17 00:00:00 2001 From: Hasanul Islam Date: Thu, 10 Jun 2021 23:06:41 +0600 Subject: [PATCH] Add/fix mypy type annotations at BFS, DFS in graphs (#4488) --- graphs/breadth_first_search.py | 4 ++-- graphs/depth_first_search.py | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/graphs/breadth_first_search.py b/graphs/breadth_first_search.py index ee9855bd0..305db01e1 100644 --- a/graphs/breadth_first_search.py +++ b/graphs/breadth_first_search.py @@ -2,12 +2,12 @@ """ Author: OMKAR PATHAK """ -from typing import Set +from typing import Dict, List, Set class Graph: def __init__(self) -> None: - self.vertices = {} + self.vertices: Dict[int, List[int]] = {} def print_graph(self) -> None: """ diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index 907cc172f..5d74a6db9 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -2,20 +2,21 @@ from __future__ import annotations +from typing import Set -def depth_first_search(graph: dict, start: str) -> set[int]: + +def depth_first_search(graph: dict, start: str) -> Set[str]: """Depth First Search on Graph :param graph: directed graph in dictionary format - :param vertex: starting vertex as a string + :param start: starting vertex as a string :returns: the trace of the search - >>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], + >>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], ... "F": ["C", "E", "G"], "G": ["F"] } - >>> start = "A" >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) - >>> all(x in output_G for x in list(depth_first_search(G, "A"))) + >>> all(x in output_G for x in list(depth_first_search(input_G, "A"))) True - >>> all(x in output_G for x in list(depth_first_search(G, "G"))) + >>> all(x in output_G for x in list(depth_first_search(input_G, "G"))) True """ explored, stack = set(start), [start]