Il Fri, 06 Mar 2009 10:19:22 +0000, mattia ha scritto: > Hi, I'm new to python, and as the title says, can I improve this snippet > (readability, speed, tricks): > > def get_fitness_and_population(fitness, population): > return [(fitness(x), x) for x in population] > > def selection(fitness, population): > ''' > Select the parent chromosomes from a population according to their > fitness (the better fitness, the bigger chance to be selected) ''' > selected_population = [] > fap = get_fitness_and_population(fitness, population) pop_len = > len(population) > # elitism (it prevents a loss of the best found solution) # take the > only 2 best solutions > elite_population = sorted(fap) > selected_population += [elite_population[pop_len-1][1]] + > [elite_population[pop_len-2][1]] > # go on with the rest of the elements for i in range(pop_len-2): > # do something
Great, the for statement has not to deal with fap anymore, but with another sequence, like this: def get_roulette_wheel(weight_value_pairs): roulette_wheel = [] for weight, value in weight_value_pairs: roulette_wheel += [value]*weight return roulette_wheel def selection(fitness, population): ... rw = get_roulette_wheel(fap) for i in range(pop_len-2): selected_population += [choice(rw)] return selected_population I think that using [choice(rw)]*len(fap) will produce the same sequence repeted len(fap) times... -- http://mail.python.org/mailman/listinfo/python-list