From 119abea4eb80c6ddcc301d7e1c5001479b1a85e1 Mon Sep 17 00:00:00 2001 From: SimpleArt <71458112+SimpleArt@users.noreply.github.com> Date: Sun, 22 Nov 2020 15:58:36 -0500 Subject: [PATCH] Using random.sample to avoid dupes --- .../survivor_selection_methods.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/survivor_selection/survivor_selection_methods.py b/src/survivor_selection/survivor_selection_methods.py index 4848c98..80c396d 100644 --- a/src/survivor_selection/survivor_selection_methods.py +++ b/src/survivor_selection/survivor_selection_methods.py @@ -17,7 +17,7 @@ class Survivor_Selection: def fill_in_best(ga): """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] @@ -25,16 +25,23 @@ class Survivor_Selection: def fill_in_random(ga): """Fills in the next population with random chromosomes from the last population""" - needed_amount = len(ga.population) - ga.population.total_children - return random.choices(ga.population, k=needed_amount) + needed_amount = len(ga.population) - len(ga.population.next_population) + return random.sample(ga.population, needed_amount) @append_to_next_population def fill_in_parents_then_random(ga): """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 - parent_amount = min(ga.population.total_parents, needed_amount) + needed_amount = len(ga.population) - len(ga.population.next_population) + parent_amount = min(len(ga.population.mating_pool), needed_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)