Skip to content

Commit 75d3807

Browse files
antmarakisnorvig
authored andcommitted
Update search.py (aimacode#680)
1 parent 6589890 commit 75d3807

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

search.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@
2323

2424
class Problem(object):
2525

26-
"""The abstract class for a formal problem. You should subclass
26+
"""The abstract class for a formal problem. You should subclass
2727
this and implement the methods actions and result, and possibly
2828
__init__, goal_test, and path_cost. Then you will create instances
2929
of your subclass and solve them with the various search functions."""
3030

3131
def __init__(self, initial, goal=None):
3232
"""The constructor specifies the initial state, and possibly a goal
33-
state, if there is a unique goal. Your subclass's constructor can add
33+
state, if there is a unique goal. Your subclass's constructor can add
3434
other arguments."""
3535
self.initial = initial
3636
self.goal = goal
@@ -708,14 +708,26 @@ def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ng
708708
population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut)
709709
for i in range(len(population))]
710710

711-
if f_thres:
712-
fittest_individual = argmax(population, key=fitness_fn)
713-
if fitness_fn(fittest_individual) >= f_thres:
714-
return fittest_individual
711+
fittest_individual = fitness_threshold(fitness_fn, f_thres, population)
712+
if fittest_individual:
713+
return fittest_individual
714+
715715

716716
return argmax(population, key=fitness_fn)
717717

718718

719+
def fitness_threshold(fitness_fn, f_thres, population):
720+
if not f_thres:
721+
return None
722+
723+
fittest_individual = argmax(population, key=fitness_fn)
724+
if fitness_fn(fittest_individual) >= f_thres:
725+
return fittest_individual
726+
727+
return None
728+
729+
730+
719731
def init_population(pop_number, gene_pool, state_length):
720732
"""Initializes population for genetic algorithm
721733
pop_number : Number of individuals in population

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy