Implement the stationary replacement operator

This commit is contained in:
coolneng 2021-06-17 23:03:03 +02:00
parent 7056534872
commit 04719dd8bc
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 24 additions and 5 deletions

View File

@ -158,15 +158,34 @@ def generational_replacement(previous_population, current_population):
return new_population
def stationary_replacement(previous_population, current_population):
new_population = previous_population
def get_best_elements(population):
first_index = population.index(max(population, key=lambda x: x.fitness))
population.pop(first_index)
second_index = population.index(max(population, key=lambda x: x.fitness))
return first_index, second_index
def get_worst_elements(population):
first_index = population.index(min(population, key=lambda x: x.fitness))
population.pop(first_index)
second_index = population.index(min(population, key=lambda x: x.fitness))
return first_index, second_index
def stationary_replacement(prev_population, current_population):
new_population = prev_population
worst_indexes = get_worst_elements(prev_population)
best_indexes = get_best_elements(current_population)
for worst, best in zip(worst_indexes, best_indexes):
if current_population[best].fitness > prev_population[worst].fitness:
new_population[worst] = current_population[best]
return new_population
def replace_population(previous_population, current_population, mode):
def replace_population(prev_population, current_population, mode):
if mode == "generational":
return generational_replacement(previous_population, current_population)
return stationary_replacement(previous_population, current_population)
return generational_replacement(prev_population, current_population)
return stationary_replacement(prev_population, current_population)
def genetic_algorithm(n, m, data, mode):