Add/fix mypy type annotations at BFS, DFS in graphs (#4488)

This commit is contained in:
Hasanul Islam 2021-06-10 23:06:41 +06:00 committed by GitHub
parent c824b90ead
commit 977511b3a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 8 deletions

View File

@ -2,12 +2,12 @@
""" Author: OMKAR PATHAK """ """ Author: OMKAR PATHAK """
from typing import Set from typing import Dict, List, Set
class Graph: class Graph:
def __init__(self) -> None: def __init__(self) -> None:
self.vertices = {} self.vertices: Dict[int, List[int]] = {}
def print_graph(self) -> None: def print_graph(self) -> None:
""" """

View File

@ -2,20 +2,21 @@
from __future__ import annotations 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 """Depth First Search on Graph
:param graph: directed graph in dictionary format :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 :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"], ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
... "F": ["C", "E", "G"], "G": ["F"] } ... "F": ["C", "E", "G"], "G": ["F"] }
>>> start = "A"
>>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) >>> 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 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 True
""" """
explored, stack = set(start), [start] explored, stack = set(start), [start]