0

So I've been trying to make a list of objects where each of the objects has a list called chromosome as an attribute. I want to fill each chromosome with 6 random numbers for my genetic algorithm. The problem I'm having is that no matter how I go about doing this, each of the objects has the same chromosome, its always has size = number of objects * 6. So if I initialize an array of 20 objects and try to print out each of their chromosomes then I will get 20 arrays that have 120 values where each array is identical instead of 20 arrays of 6 values where each array is unique.

Here's the code:

class Individual:

    def __init__(self, chromosome = [], fitness = [], number_of_genes = 6):
        self.fitness = fitness
        self.number_of_genes = number_of_genes
        self.chromosome = chromosome
        for i in range(self.number_of_genes):
            x = random.uniform(0.0,1.0)
            self.chromosome.append(x)


    def print_chromosome(self):
        print(self.chromosome)

Then, in my main program I use:

population = 10
def init_individuals(population):
    return [Individual() for i in range(population)]

        
def print_individuals(individuals):
    for i in range(len(individuals)):
        individuals[i].print_chromosome()

individuals = init_individuals(population)
print_individuals(individuals)

Ive tried making the random number generator in its own function and I also tried making my main functions into class functions instead and I get the same result.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • In short, the list set as default argument is always the same instance. Instead do `chromosome=None` and create the list in the method body, if chromosome is None. – Wups Oct 13 '20 at 07:17
  • @Wups Thanks, that fix works. Using your explanation I also found that I can pass in the array when I make the object like object=Individual(chromosome = [ ]) and that also works. – bigb123 Oct 13 '20 at 07:22

0 Answers0