Skip to content

Commit 104311f

Browse files
Add missing type hints to hill_climbing.py
This commit adds the missing type annotations to searches/hill_climbing.py. - Added type annotation for function_to_optimize using Callable [[int, int], int] - Added return type hints to get_neighbors, __hash__, __eq__, and __str__ - Added missing type hint for search_prob in hill_climbing() - Improved type clarity while preserving existing logic - Used modern Python type hints (PEP 585) This improves readability and typing consistency across the repository.
1 parent 678dedb commit 104311f

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

searches/hill_climbing.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
# https://en.wikipedia.org/wiki/Hill_climbing
22
import math
3-
3+
from collections.abc import Callable
44

55
class SearchProblem:
66
"""
77
An interface to define search problems.
88
The interface will be illustrated using the example of mathematical function.
99
"""
1010

11-
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
11+
def __init__(
12+
self,
13+
x: int,
14+
y: int,
15+
step_size: int,
16+
function_to_optimize: Callable[[int, int], int]
17+
) -> None:
1218
"""
1319
The constructor of the search problem.
1420
@@ -34,7 +40,7 @@ def score(self) -> int:
3440
"""
3541
return self.function(self.x, self.y)
3642

37-
def get_neighbors(self):
43+
def get_neighbors(self) -> list["SearchProblem"]:
3844
"""
3945
Returns a list of coordinates of neighbors adjacent to the current coordinates.
4046
@@ -58,21 +64,21 @@ def get_neighbors(self):
5864
)
5965
]
6066

61-
def __hash__(self):
67+
def __hash__(self) -> int:
6268
"""
6369
hash the string representation of the current search state.
6470
"""
6571
return hash(str(self))
6672

67-
def __eq__(self, obj):
73+
def __eq__(self, obj: object) -> bool:
6874
"""
6975
Check if the 2 objects are equal.
7076
"""
7177
if isinstance(obj, SearchProblem):
7278
return hash(str(self)) == hash(str(obj))
7379
return False
7480

75-
def __str__(self):
81+
def __str__(self) -> str:
7682
"""
7783
string representation of the current search state.
7884
>>> str(SearchProblem(0, 0, 1, None))
@@ -84,7 +90,7 @@ def __str__(self):
8490

8591

8692
def hill_climbing(
87-
search_prob,
93+
search_prob: SearchProblem,
8894
find_max: bool = True,
8995
max_x: float = math.inf,
9096
min_x: float = -math.inf,

0 commit comments

Comments
 (0)