Roulette wheel

mattia gervaz at gmail.com
Wed Mar 4 13:02:05 EST 2009


Hi everyone, I'm new to python and I want to create some simple code in 
order to code the classical genetic algorithm example: given a population 
of chromosomes, encoded using 1 and 0, find the chromosome with the 
maximum number of 1s. Now, despite all the code used to implement the 
solution, I'm wondering if there is a better way to use the so-called 
roulette wheel selection in this problem. Here I paste the code of my 
solution, any advice will be helpful:

from random import randint, random

def create_chromosome(min, max, length):
    chromosome = []
    for i in range(length):
        chromosome.append(randint(min, max))
    return chromosome

def fitness(chrm, ffunc=sum):
    return ffunc(chrm)

def create_population(nelem, min, max, length):
    return [create_chromosome(min, max, length) for i in range(nelem)]    

def get_fitness_and_population(population):
    return [(fitness(x), x) for x in population]
    
def get_roulette_wheel(population):
    roulette_wheel = []
    index = 0
    
    for x in get_fitness_and_population(population):
        for j in range(x[0]):
            roulette_wheel.append(index)
        index += 1
        
    return roulette_wheel

pop = create_population(5, 0, 1, 10)    
rw = get_roulette_wheel(pop)
print(rw)
print(len(rw))
ri = randint(0, len(rw) - 1)
print("Random index:", rw[ri], ", value:", pop[rw[ri]])



More information about the Python-list mailing list