Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion data_structures/hashing/hash_table_with_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def _set_value(self, key, data):
self.values[key] = deque([]) if self.values[key] is None else self.values[key]
self.values[key] = deque() if self.values[key] is None else self.values[key]
self.values[key].appendleft(data)
self._keys[key] = self.values[key]

Expand Down
19 changes: 13 additions & 6 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],
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work adding these hints!

I have one suggestion regarding function_to_optimize: Currently, it is typed to return an int (Callable[[int, int], int]). However, in optimization problems, objective functions very often return float values (costs, fitness scores, etc.).

Restricting it to int might flag valid use cases as errors. Would it be safer to type it as Callable[[int, int], float] or Callable[[int, int], int | float]?

) -> None:
"""
The constructor of the search problem.

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