Cleaned up list usage

This commit is contained in:
SimpleArt
2020-11-19 18:02:07 -05:00
parent 7511429228
commit 3412c05da2
3 changed files with 22 additions and 16 deletions

View File

@ -33,7 +33,7 @@ class Mutation_Methods:
def individual_genes(ga, old_chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
chromosome = ga.make_chromosome(old_chromosome.get_gene_list())
chromosome = ga.make_chromosome(list(old_chromosome))
# Loops until enough mutations occur
for n in range(ceil(len(chromosome)*ga.gene_mutation_rate)):
@ -61,7 +61,7 @@ class Mutation_Methods:
def swap_genes(ga, old_chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
chromosome = ga.make_chromosome(old_chromosome.get_gene_list())
chromosome = ga.make_chromosome(list(old_chromosome))
# Loops until enough mutations occur
for n in range(ceil(len(chromosome)*ga.gene_mutation_rate)):

View File

@ -57,7 +57,7 @@ class Chromosome:
def __iter__(self):
"""Returns an iterable of the gene list"""
return iter(self.gene_list)
return self.gene_list
def __getitem__(self, k):
@ -75,11 +75,25 @@ class Chromosome:
return len(self.gene_list)
def __contains__(self, searched_gene):
"""Returns True if the chromosome contains the gene and False otherwise.
Ex. if chromosome in ga.population: ..."""
return (searched_gene in self.gene_list)
def index_of(self, searched_gene):
"""Returns the index of the gene in the current chromosome.
Returns -1 if no index found."""
return self.gene_list.index(searched_gene)
def __repr__(self):
"""Create a backend string of the chromosome. Ex '1, 2, 3'."""
return ', '.join(repr(gene) for gene in self.gene_list)
return ', '.join(repr(gene) for gene in self)
def __str__(self):
"""Create a printable string of the chromosome. Ex '[1][2][3]'."""
return ''.join(str(gene) for gene in self.gene_list)
return ''.join(str(gene) for gene in self)

View File

@ -153,7 +153,7 @@ class Population:
def __iter__(self):
"""Returns an iterable of chromosomes"""
return iter(self.chromosome_list)
return self.chromosome_list
def __getitem__(self, k):
@ -175,22 +175,14 @@ class Population:
"""Returns True if the current population contains the chromosome and False otherwise.
Ex. if chromosome in ga.population: ..."""
for index in range(len(self)):
if self[index] == searched_chromosome:
return True
else:
return False
return (searched_chromosome in self.chromosome_list)
def index_of(self, searched_chromosome):
"""Returns the index of the chromosome in the current population.
Returns -1 if no index found."""
for index in range(len(self)):
if self[index] == searched_chromosome:
return index
else:
return -1
return self.chromosome_list.index(searched_chromosome)
def __repr__(self):