list index out of range, genetic algorithm

Asked

Viewed 63 times

0

I’m having trouble with the line you’re on parcial += pacum [i-1] I am with the error "list index out of range", about the variables and lists: list population and fitness depend on the sizePopulation 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
  • Your while is running more times than the amount of elements in pacnum.

  • Yes exact, but how to solve? because I don’t understand why it is getting bigger, until I decreased a position of the Len function.

1 answer

1

Good for anyone who wants to use problem solving, I solved 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.