Using random.sample to avoid dupes

This commit is contained in:
SimpleArt
2020-11-22 15:58:36 -05:00
parent cdc2b6bdfb
commit 119abea4eb

View File

@ -17,7 +17,7 @@ class Survivor_Selection:
def fill_in_best(ga): def fill_in_best(ga):
"""Fills in the next population with the best chromosomes from the last population""" """Fills in the next population with the best chromosomes from the last population"""
needed_amount = len(ga.population) - ga.population.total_children needed_amount = len(ga.population) - len(ga.population.next_population)
return ga.population[:needed_amount] return ga.population[:needed_amount]
@ -25,16 +25,23 @@ class Survivor_Selection:
def fill_in_random(ga): def fill_in_random(ga):
"""Fills in the next population with random chromosomes from the last population""" """Fills in the next population with random chromosomes from the last population"""
needed_amount = len(ga.population) - ga.population.total_children needed_amount = len(ga.population) - len(ga.population.next_population)
return random.choices(ga.population, k=needed_amount) return random.sample(ga.population, needed_amount)
@append_to_next_population @append_to_next_population
def fill_in_parents_then_random(ga): def fill_in_parents_then_random(ga):
"""Fills in the next population with all parents followed by random chromosomes from the last population""" """Fills in the next population with all parents followed by random chromosomes from the last population"""
needed_amount = len(ga.population) - ga.population.total_children needed_amount = len(ga.population) - len(ga.population.next_population)
parent_amount = min(ga.population.total_parents, needed_amount) parent_amount = min(len(ga.population.mating_pool), needed_amount)
random_amount = needed_amount - parent_amount random_amount = needed_amount - parent_amount
return ga.population.get_mating_pool()[:parent_amount] + random.choices(ga.population, k=random_amount) # Only parents are used.
if random_amount == 0:
return ga.population.mating_pool[:parent_amount]
# Parents need to be removed from the random sample to avoid dupes.
else:
return ga.population.mating_pool +\
random.sample(set(ga.population)-set(ga.population.mating_pool), random_amount)