From 5f8779f1a6eadabaadd7145467128a068bff3916 Mon Sep 17 00:00:00 2001 From: Sepehr Madani <ssepehrmadani@gmail.com> Date: Sat, 1 Aug 2020 19:08:07 -0400 Subject: [PATCH] Remove duplicate chromosomes by genes' hash-values --- algorithms/genetic_algorithm.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/algorithms/genetic_algorithm.py b/algorithms/genetic_algorithm.py index 84efd87..17ba233 100644 --- a/algorithms/genetic_algorithm.py +++ b/algorithms/genetic_algorithm.py @@ -154,6 +154,15 @@ class GeneticAlgorithm(BaseAlgorithm): ) chromosome.needs_update = False + # Remove redundant chromosomes + hash_list = [] + for chromosome in self.chromosomes: + this_hash = hash(chromosome) + if this_hash in hash_list: + chromosome = Chromosome() + else: + hash_list.append(this_hash) + # Sort sample by chromosome score self.chromosomes.sort(key=lambda x: x.get_score(), reverse=True) @@ -175,7 +184,6 @@ class GeneticAlgorithm(BaseAlgorithm): for idx, original in enumerate(self.chromosomes[1:self.sample_size + 1]): mutated = self.chromosomes[idx + self.sample_size - 1] mutated.gene = original.gene.copy() - mutated.needs_update = True mutated.mutate() def make_weights(self, chromosome): -- GitLab