Skip to content

Commit a4b7d12

Browse files
authored
Fix mypy errors at greedy best first algo (TheAlgorithms#4575)
1 parent c5003a2 commit a4b7d12

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

graphs/greedy_best_first.py

+24-11
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
from __future__ import annotations
66

7+
from typing import Optional
8+
9+
Path = list[tuple[int, int]]
10+
711
grid = [
812
[0, 0, 0, 0, 0, 0, 0],
913
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
@@ -33,7 +37,15 @@ class Node:
3337
True
3438
"""
3539

36-
def __init__(self, pos_x, pos_y, goal_x, goal_y, g_cost, parent):
40+
def __init__(
41+
self,
42+
pos_x: int,
43+
pos_y: int,
44+
goal_x: int,
45+
goal_y: int,
46+
g_cost: float,
47+
parent: Optional[Node],
48+
):
3749
self.pos_x = pos_x
3850
self.pos_y = pos_y
3951
self.pos = (pos_y, pos_x)
@@ -72,16 +84,16 @@ class GreedyBestFirst:
7284
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
7385
"""
7486

75-
def __init__(self, start, goal):
87+
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
7688
self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)
7789
self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)
7890

7991
self.open_nodes = [self.start]
80-
self.closed_nodes = []
92+
self.closed_nodes: list[Node] = []
8193

8294
self.reached = False
8395

84-
def search(self) -> list[tuple[int]]:
96+
def search(self) -> Optional[Path]:
8597
"""
8698
Search for the path,
8799
if a path is not found, only the starting position is returned
@@ -113,8 +125,9 @@ def search(self) -> list[tuple[int]]:
113125
else:
114126
self.open_nodes.append(better_node)
115127

116-
if not (self.reached):
128+
if not self.reached:
117129
return [self.start.pos]
130+
return None
118131

119132
def get_successors(self, parent: Node) -> list[Node]:
120133
"""
@@ -143,7 +156,7 @@ def get_successors(self, parent: Node) -> list[Node]:
143156
)
144157
return successors
145158

146-
def retrace_path(self, node: Node) -> list[tuple[int]]:
159+
def retrace_path(self, node: Optional[Node]) -> Path:
147160
"""
148161
Retrace the path from parents to parents until start node
149162
"""
@@ -166,9 +179,9 @@ def retrace_path(self, node: Node) -> list[tuple[int]]:
166179

167180
greedy_bf = GreedyBestFirst(init, goal)
168181
path = greedy_bf.search()
182+
if path:
183+
for pos_x, pos_y in path:
184+
grid[pos_x][pos_y] = 2
169185

170-
for elem in path:
171-
grid[elem[0]][elem[1]] = 2
172-
173-
for elem in grid:
174-
print(elem)
186+
for elem in grid:
187+
print(elem)

0 commit comments

Comments
 (0)