Skip to content
Merged
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -1351,6 +1351,7 @@
* [Capitalize](strings/capitalize.py)
* [Check Anagrams](strings/check_anagrams.py)
* [Count Vowels](strings/count_vowels.py)
* [Count Vowels Consonants](strings/count_vowels_consonants.py)
* [Credit Card Validator](strings/credit_card_validator.py)
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)
Expand Down
21 changes: 14 additions & 7 deletions searches/hill_climbing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# https://en.wikipedia.org/wiki/Hill_climbing
import math
from collections.abc import Callable


class SearchProblem:
Expand All @@ -8,7 +9,13 @@ class SearchProblem:
The interface will be illustrated using the example of mathematical function.
"""

def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
def __init__(
self,
x: int,
y: int,
step_size: int,
function_to_optimize: Callable[[int, int], int | float],
) -> None:
"""
The constructor of the search problem.

Expand All @@ -22,7 +29,7 @@ def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
self.step_size = step_size
self.function = function_to_optimize

def score(self) -> int:
def score(self) -> int | float:
"""
Returns the output of the function called with current x and y coordinates.
>>> def test_function(x, y):
Expand All @@ -34,7 +41,7 @@ def score(self) -> int:
"""
return self.function(self.x, self.y)

def get_neighbors(self):
def get_neighbors(self) -> list["SearchProblem"]:
"""
Returns a list of coordinates of neighbors adjacent to the current coordinates.

Expand All @@ -58,21 +65,21 @@ def get_neighbors(self):
)
]

def __hash__(self):
def __hash__(self) -> int:
"""
hash the string representation of the current search state.
"""
return hash(str(self))

def __eq__(self, obj):
def __eq__(self, obj: object) -> bool:
"""
Check if the 2 objects are equal.
"""
if isinstance(obj, SearchProblem):
return hash(str(self)) == hash(str(obj))
return False

def __str__(self):
def __str__(self) -> str:
"""
string representation of the current search state.
>>> str(SearchProblem(0, 0, 1, None))
Expand All @@ -84,7 +91,7 @@ def __str__(self):


def hill_climbing(
search_prob,
search_prob: SearchProblem,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
Expand Down
Loading