Home > Software design >  Randomly generated integers in a list are the same
Randomly generated integers in a list are the same

Time:04-23

I'm having this problem with my script. I want to initialize a genetic algorithm, and in this case I want to give every first element in the row a random value between 200 and 400.

import random

def InitiatePopulation(Population,AmountofSettings):
    Generation= [None]*Population
    sett = []
    for k in range(0,Population):
        for j in range(0,AmountofSettings):
            sett.append(300)
        Generation[k] = sett
    for _k in range(0, len(Generation)):
        Generation[_k][0] = random.randint(200,400)
        for _p in range(1, len(Generation[_k]),3):
            Generation[_k][_p] = 20
    return Generation

Whenever I run the code, all first values all are the same values. i tried adjusting the seed value, but that doesnt work. Because I have had problems in the past with for loops, the problem could be there was well. I understand the code isnt necessarily efficient, I just wanted to get to the creation of the population before the adjustment of the first setting variable to a random integer.

output:

[[221, 20, 300, 300, 20, 300, 300, 20, 300, 300, 20, 300], [221, 20, 300, 300, 20, 300, 300, 20, 300, 300, 20, 300]]

The expected output would be the same, except with the 221 values being different from each other. How can I achieve this?

CodePudding user response:

It looks like the issue is that you're setting all of the elements of Generation to be the same list (i.e. referring to the same location in memory).

You need to reassign the list to a new empty list at the start of each iteration:

for k in range(0,Population):
    sett = []
    for j in range(0,AmountofSettings):
        sett.append(300)
    Generation[k] = sett

CodePudding user response:

I realize that it was answered, I'm just providing a slightly optimized solution if you need it. I removed 2 for loops and now it's one loop with a list comprehension outside since it only needs to run once.

import random

def InitiatePopulation(Population, AmountofSettings):
    Generation = []
    sett = [20 if (x-1) % 3 == 0 else 300 for x in range(AmountofSettings)]
    
    for _ in range(Population):
        _sett = sett.copy()
        _sett[0] = random.randint(200,400)
        Generation.append(_sett)
               
    return Generation

print(InitiatePopulation(2, 12))
  • Related