From 307ffd8c29d1b2b156c349fde424e62e8493428a Mon Sep 17 00:00:00 2001 From: Hasanul Islam Date: Mon, 12 Jul 2021 12:10:07 +0600 Subject: [PATCH] Fix mypy errors at bidirectional_bfs (#4531) --- graphs/bidirectional_breadth_first_search.py | 25 ++++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/graphs/bidirectional_breadth_first_search.py b/graphs/bidirectional_breadth_first_search.py index 39d8dc7d4..9b84ab21b 100644 --- a/graphs/bidirectional_breadth_first_search.py +++ b/graphs/bidirectional_breadth_first_search.py @@ -5,6 +5,9 @@ https://en.wikipedia.org/wiki/Bidirectional_search from __future__ import annotations import time +from typing import Optional + +Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], @@ -20,7 +23,9 @@ delta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class Node: - def __init__(self, pos_x, pos_y, goal_x, goal_y, parent): + def __init__( + self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Optional[Node] + ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) @@ -45,14 +50,14 @@ class BreadthFirstSearch: (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)] """ - def __init__(self, start, goal): + def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], None) self.target = Node(goal[1], goal[0], goal[1], goal[0], None) self.node_queue = [self.start] self.reached = False - def search(self) -> list[tuple[int]]: + def search(self) -> Optional[Path]: while self.node_queue: current_node = self.node_queue.pop(0) @@ -65,8 +70,9 @@ class BreadthFirstSearch: for node in successors: self.node_queue.append(node) - if not (self.reached): - return [(self.start.pos)] + if not self.reached: + return [self.start.pos] + return None def get_successors(self, parent: Node) -> list[Node]: """ @@ -87,7 +93,7 @@ class BreadthFirstSearch: ) return successors - def retrace_path(self, node: Node) -> list[tuple[int]]: + def retrace_path(self, node: Optional[Node]) -> Path: """ Retrace the path from parents to parents until start node """ @@ -119,7 +125,7 @@ class BidirectionalBreadthFirstSearch: self.bwd_bfs = BreadthFirstSearch(goal, start) self.reached = False - def search(self) -> list[tuple[int]]: + def search(self) -> Optional[Path]: while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: current_fwd_node = self.fwd_bfs.node_queue.pop(0) current_bwd_node = self.bwd_bfs.node_queue.pop(0) @@ -144,10 +150,9 @@ class BidirectionalBreadthFirstSearch: if not self.reached: return [self.fwd_bfs.start.pos] + return None - def retrace_bidirectional_path( - self, fwd_node: Node, bwd_node: Node - ) -> list[tuple[int]]: + def retrace_bidirectional_path(self, fwd_node: Node, bwd_node: Node) -> Path: fwd_path = self.fwd_bfs.retrace_path(fwd_node) bwd_path = self.bwd_bfs.retrace_path(bwd_node) bwd_path.pop()