list index out of range, genetic algorithm

0

I'm having problems on the line that is parcial += pacum [i-1] I'm getting the error "list index out of range", about the variables and lists: Population and fitness list depend on the size Population that can be any integer value.

def selecao(fitness, populacao):
    populacaoIntermediaria=[]
    somatotal = sum(fitness)
    probSelecao = []
    pacum = []

    for j in range(len(fitness)):
        probSelecao.append(fitness[j]/somatotal)
        pacum.append(sum(probSelecao))
        print('Pacum({}): {}'.format(j, pacum[j]))

    for j in range(tamPopulacao):

        i = 1
        parcial = 0
        r = uniform(0, somatotal)

        while (r >= parcial or i == len(pacum)):
            print('Posição{}'.format(i))
            parcial += pacum[i-1]
            i += 1

            print('Parcial: {}'.format(parcial))
        populacaoIntermediaria.append(populacao[i-1])

    print('População Intermediaria: {}'.format(populacaoIntermediaria))

    return  populacaoIntermediaria
    
asked by anonymous 21.05.2018 / 03:47

1 answer

1

Good for anyone who wants to use problem solving, I decided it was a logic problem. Fixed code:

def selecao(fitness, populacao):
    populacaoIntermediaria=[]
    somatotal = sum(fitness)
    probSelecao = []
    pacum = []

    for j in range(0, len(fitness)):
        probSelecao.append(fitness[j]/somatotal)
        pacum.append(sum(probSelecao))

        print('Pacum({}): {}'.format(j, pacum[j]))

    for j in range(tamPopulacao):

        i = 0
        parcial = 0
        r = uniform(0, somatotal)

        while (i != len(pacum)):
            print('Parcial ({}): {}'.format(i, parcial))
            parcial += pacum[i]
            i += 1
            if (parcial >= r):
                 break
        populacaoIntermediaria.append(populacao[i-1])

    print('População Intermediaria: {}'.format(populacaoIntermediaria))

    return  populacaoIntermediaria
    
22.05.2018 / 00:55