MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / SearchProblem

Class SearchProblem

searches/hill_climbing.py:5–83  ·  view source on GitHub ↗

An interface to define search problems. The interface will be illustrated using the example of mathematical function.

Source from the content-addressed store, hash-verified

3
4
5class SearchProblem:
6 """
7 An interface to define search problems.
8 The interface will be illustrated using the example of mathematical function.
9 """
10
11 def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
12 """
13 The constructor of the search problem.
14
15 x: the x coordinate of the current search state.
16 y: the y coordinate of the current search state.
17 step_size: size of the step to take when looking for neighbors.
18 function_to_optimize: a function to optimize having the signature f(x, y).
19 """
20 self.x = x
21 self.y = y
22 self.step_size = step_size
23 self.function = function_to_optimize
24
25 def score(self) -> int:
26 """
27 Returns the output of the function called with current x and y coordinates.
28 >>> def test_function(x, y):
29 ... return x + y
30 >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0
31 0
32 >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12
33 12
34 """
35 return self.function(self.x, self.y)
36
37 def get_neighbors(self):
38 """
39 Returns a list of coordinates of neighbors adjacent to the current coordinates.
40
41 Neighbors:
42 | 0 | 1 | 2 |
43 | 3 | _ | 4 |
44 | 5 | 6 | 7 |
45 """
46 step_size = self.step_size
47 return [
48 SearchProblem(x, y, step_size, self.function)
49 for x, y in (
50 (self.x - step_size, self.y - step_size),
51 (self.x - step_size, self.y),
52 (self.x - step_size, self.y + step_size),
53 (self.x, self.y - step_size),
54 (self.x, self.y + step_size),
55 (self.x + step_size, self.y - step_size),
56 (self.x + step_size, self.y),
57 (self.x + step_size, self.y + step_size),
58 )
59 ]
60
61 def __hash__(self):
62 """

Callers 3

get_neighborsMethod · 0.85
hill_climbing.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected