Problem with tuple

3

Good, we have done this method of genetic algorithms in Python 3 but we have a problem of assignment to the tuple. We have read that a solution could be to convert the tuple to list but we do not know how to do it.

def selection_and_reproduction(poblacionNueva):

    #Puntua todos los elementos de la poblacion (poblacionNueva) y se queda con los mejores
    #guardandolos dentro de 'selected'.
    #Despues mezcla el material genetico de los elegidos para crear nuevos individuos y
    #llenar la poblacion (guardando tambien una copia de los individuos seleccionados sin
    #modificar).

    #Por ultimo muta a los individuos.


     puntuados = [ (calcularFitness(i), i) for i in poblacionNueva]
     def takeSecond(puntuados):
         return puntuados[1]
     puntuados = sorted(puntuados, key=takeSecond) 

     poblacionNueva = puntuados


     selected =  puntuados[(len(puntuados)-indAReproducir):]
     for i in range(len(poblacionNueva)-indAReproducir):
         punto = random.randint(1,largo-1) 
         padre = random.sample(selected, 2) 
         poblacionNueva[i][:punto] = padre[0][:punto] 
         poblacionNueva[i][punto:] = padre[1][punto:] 

     return poblacionNueva 

The error that comes to us is the following:

    
asked by Carlos Lozano 14.07.2017 в 17:22
source

1 answer

3

That happens because the tuples are immutable , that is, once defined you can not modify them. Currently your variable puntuados is a list of tuples:

puntuados = [ (calcularFitness(i), i) for i in poblacionNueva]

What you can do, simply, is change it to a list of lists:

puntuados = [ [calcularFitness(i), i] for i in poblacionNueva]
    
answered by 14.07.2017 в 17:29