Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4989ff7

Browse files
committed
Fixed local-search algorithms. Could be prettier but should work now for the first time.
1 parent 07a1154 commit 4989ff7

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

search.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def path_cost(self, c, state1, action, state2):
4646
and action. The default method costs 1 for every step in the path."""
4747
return c + 1
4848

49-
def value(self):
49+
def value(self, state):
5050
"""For optimization problems, each state has a value. Hill-climbing
5151
and related algorithms try to maximize this value."""
5252
abstract
@@ -247,10 +247,14 @@ def hill_climbing(problem):
247247
stopping when no neighbor is better. [Fig. 4.11]"""
248248
current = Node(problem.initial)
249249
while True:
250-
neighbor = argmax(current.expand(problem), Node.value)
251-
if neighbor.value() <= current.value():
252-
return current.state
250+
neighbors = current.expand(problem)
251+
if not neighbors:
252+
break
253+
neighbor = argmax(neighbors, lambda node: problem.value(node.state))
254+
if problem.value(neighbor.state) <= problem.value(current.state):
255+
break
253256
current = neighbor
257+
return current.state
254258

255259
def exp_schedule(k=20, lam=0.005, limit=100):
256260
"One possible schedule function for simulated annealing"
@@ -263,8 +267,11 @@ def simulated_annealing(problem, schedule=exp_schedule()):
263267
T = schedule(t)
264268
if T == 0:
265269
return current
266-
next = random.choice(current.expand(problem))
267-
delta_e = next.path_cost - current.path_cost
270+
neighbors = current.expand(problem)
271+
if not neighbors:
272+
return current
273+
next = random.choice(neighbors)
274+
delta_e = problem.value(next.state) - problem.value(current.state)
268275
if delta_e > 0 or probability(math.exp(delta_e/T)):
269276
current = next
270277

0 commit comments

Comments
 (0)