How to refresh a dictionary with random values?

Mythaar :

I'm working on a genetic algorithm based on tournament selection, and need to run several populations at once. My problem is that I have a dictionary with random values for the individuals, but when I make a loop checking for these values they are the same.

Is there any way to refresh a dictionary so the random values are changed?

My dictionary:

individuals = {

    'a': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'b': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'c': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'd': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'e': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'f': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'g': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'h': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)],
    'i': [random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4),random.randint(-4,4)]
}

My loop:

def run_generation():
    global random_individuals, fitness_scores
    for k in range(tournamentSize):
        randchoice = random.sample(list(individuals), 1)[0] #update individual list so values are different??!
        randchoice = individuals.get(randchoice)
        random_individuals.append(randchoice)

Currently, I'm just redefining the dictionary each time I form a new population (just copy-pasting the dictionary), but that seems uneconomical and would be sluggish once the population grows larger.

lenik :

You may easily generate your dictionary on the fly using simple list comprehensions:

individuals = { i : [random.randint(-4,4) for _ in range(6)] for i in 'abcdefghi' }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33368&siteId=1