Is there a better way of doing this?

Chris Rebert clp2 at rebertia.com
Fri Mar 6 05:32:33 EST 2009


On Fri, Mar 6, 2009 at 2:19 AM, mattia <gervaz at gmail.com> wrote:
> 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

Removing the unnecessary use of sorted() and using list.pop() rather
than explicit indices:

def selection(fitness, population):
   '''
   Select the parent chromosomes from a population according to their
   fitness (the better fitness, the bigger chance to be selected)
   '''
   fap = get_fitness_and_population(fitness, population)
   fap.sort()
   # elitism (it prevents a loss of the best found solution)
   # take the only 2 best solutions
   selected_population = [fap.pop()[1] for i in range(2)]

   # go on with the rest of the elements
   for fit, pop in fap:
       #do something

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list