Fix max and min selection according to fitness

This commit is contained in:
coolneng 2021-06-18 20:06:59 +02:00
parent ccf3a18a59
commit 04fd66425e
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 8 additions and 6 deletions

View File

@ -156,24 +156,26 @@ def tournament_selection(m, population):
def generational_replacement(previous_population, current_population): def generational_replacement(previous_population, current_population):
new_population = current_population new_population = current_population
best_previous_individual = max(previous_population, key=lambda x: x.fitness) best_previous_individual = max(previous_population, key=lambda x: all(x.fitness))
if best_previous_individual not in new_population: if best_previous_individual not in new_population:
worst_index = new_population.index(min(new_population, key=lambda x: x.fitness)) worst_index = new_population.index(
min(new_population, key=lambda x: all(x.fitness))
)
new_population[worst_index] = best_previous_individual new_population[worst_index] = best_previous_individual
return new_population return new_population
def get_best_elements(population): def get_best_elements(population):
first_index = population.index(max(population, key=lambda x: x.fitness)) first_index = population.index(max(population, key=lambda x: all(x.fitness)))
population.pop(first_index) population.pop(first_index)
second_index = population.index(max(population, key=lambda x: x.fitness)) second_index = population.index(max(population, key=lambda x: all(x.fitness)))
return first_index, second_index return first_index, second_index
def get_worst_elements(population): def get_worst_elements(population):
first_index = population.index(min(population, key=lambda x: x.fitness)) first_index = population.index(min(population, key=lambda x: all(x.fitness)))
population.pop(first_index) population.pop(first_index)
second_index = population.index(min(population, key=lambda x: x.fitness)) second_index = population.index(min(population, key=lambda x: all(x.fitness)))
return first_index, second_index return first_index, second_index