|
23 | 23 |
|
24 | 24 | class Problem(object):
|
25 | 25 |
|
26 |
| - """The abstract class for a formal problem. You should subclass |
| 26 | + """The abstract class for a formal problem. You should subclass |
27 | 27 | this and implement the methods actions and result, and possibly
|
28 | 28 | __init__, goal_test, and path_cost. Then you will create instances
|
29 | 29 | of your subclass and solve them with the various search functions."""
|
30 | 30 |
|
31 | 31 | def __init__(self, initial, goal=None):
|
32 | 32 | """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 |
34 | 34 | other arguments."""
|
35 | 35 | self.initial = initial
|
36 | 36 | self.goal = goal
|
@@ -708,14 +708,26 @@ def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ng
|
708 | 708 | population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut)
|
709 | 709 | for i in range(len(population))]
|
710 | 710 |
|
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 | + |
715 | 715 |
|
716 | 716 | return argmax(population, key=fitness_fn)
|
717 | 717 |
|
718 | 718 |
|
| 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 | + |
719 | 731 | def init_population(pop_number, gene_pool, state_length):
|
720 | 732 | """Initializes population for genetic algorithm
|
721 | 733 | pop_number : Number of individuals in population
|
|
0 commit comments