-4

I'm having problems with my code and I know this problem is simple but I just can't figure it out how to solve it, I'll really appreciate if someone could tell me what I'm doing wrong:

            import random
            from math import *
            def create_population(dim,pn):
                t = log(factorial(dim**2),2)
                b = int(t+1)
                d = ""
                indarray = []
                bits_array=[]
                #print("bits usados: ",b)
                for x in range(pn):
                    for y in range(b) :
                        if random.randint(0,400000) %2:
                            d = "1"+d
                        else:
                            d="0"+d

                        num=int(d,2)%factorial(dim**2)
                    bits_array.append(d)
                    indarray.append(num)

                    #print("\n index #",len(indarray),": ",num)
                    d=""
                return indarray,dim,bits_array,b

            def i2ms(index,b):
                squares=[]
                a=init_a(b)
                i=0
                t=b
                b = (b**2)-1
                for i in range(len(index)):
                    s=""
                    cont = 1
                    while(index[i]>0):
                        c = factorial(b)
                        ind =(index[i]/c)
                        s = s+str(a[int(ind)])+" "
                        del a[(int(ind))]
                        index[i] = index[i]%c
                        b-=1
                        cont +=1
                    for i in range(len(a)):
                        s = s+str(a[i])+" "
                    squares.append(s)
                    a = init_a(t)
                    b = t
                    b = (b**2)-1
                    s=""
                return squares
            def init_a(b):
                a=[]
                for i in range(b**2):
                    a.append(i+1)
                return a
            def score(squares):
                scores=[]
                print("\n")
                for i in range(len(squares)):
                    r = squares[i]
                    r = r.split(' ')
                    n = int(sqrt(len(r)))
                    nd = r
                    goal = n * (n * n + 1) / 2;
                    nd.reverse()
                    m = [[nd.pop() for i in range(n)] for j in range(n)]
                    #print ("Cubo #",i+1,": \n")
                    #for i in range(n):
                        #print(m[i],'\n')
                    min_sum,max_sum= 0,0
                    minn = 1
                    maxx = n * n
                    for i in range (n):
                        min_sum += minn
                        minn += 1
                        max_sum += maxx
                        maxx += 1
                    min_b,max_b = abs(goal - min_sum), abs(goal - max_sum)
                    if min_sum < max_sum:
                         final_b = max_sum
                    else:
                        final_b = min_sum
                    total_cases = 2 * n + 2
                    bias = total_cases * final_b
                    fitness = bias
                    #print ("Max score: ",fitness)
                    for i in range(n):
                        s =0
                        for j in range(n):
                            s +=int(m[i][j])
                        fitness -= abs(goal-s)
                    for j in range(n):
                        s=0
                        for i in range(n):
                            s += int(m[i][j])
                        fitness -= abs(goal-s)
                    s = 0

                    if n%2 == 1:
                        for i in range(n):
                            s+= int(m[i][i])
                        fitness -= abs(goal-s)
                        m.reverse()
                        s = 0
                        for i in range(n):
                            s+= int(m[i][i])
                        fitness -= abs(goal-s)

                    #print("Actual score: ",fitness,"\n")
                    scores.append(int(fitness))
                #print("goal",goal)
                return scores,bias

            def breed(popul,score,breed_size,b):#popul= la poblacion , score : sus notas ind, breed_size, tamaño de poblacion que esco
            #escogeremos, b numero de bites;
            #Calculamos las medidas de la poblacion a "mergear"
                print(popul)
                print(score)
                maxx = max(score)
                #Acomodamos los cubos(en binario) con su respectivo score
                breed_pop=[]
                new_pop=[]
                for y in range(breed_size):
                    for z in score:
                        if score[z] == maxx:
                            breed_pop.append(popul[z])
                            del score[z]
                            del popul[z]
                        maxx= max(score)
                        print(breed_pop)


                if breed_pop>breed_size:
                    breed_pop.pop()
                    print(breed_pop)
                ##sorted(pop_dict.values())
            if __name__ == '__main__':
                #Dar Dimensiones y determinar la poblacion inicial
                print("dimensiones?")
                n = input()
                print("poblacion?")
                pn = input()
                print("breed size?")
                p= int(input())
                ##g = input()
                #Pasar los datos de dim y pob por el metodo de create_population, devuelve una lista con los index del cubo y su dimensiones
                ind,b,bits_a,bitsn= create_population(int(n),int(pn))
                #Convertimos cada uno de esos indices a un cubo magico con i2ms, devuelve un array de cubos magicos
                squares = i2ms(ind,b)
                '''print("\n")
                for i in range(len(squares)):
                    print("Cubo #",i+1,": " , squares[i])
                    #Pasamos cada cubo por score, nos dara el puntaje de cada cubo, devuelve una lista con los scores y el puntaje maximo
                '''
                scores,perfect = score(squares)
                breed(bits_a,scores,p,bitsn)
                '''for y in range(len(scores)):
                    print(scores[y],"/",perfect)
            '''

I'm using dimension = 3, population =10, and breed_size=4 but I keep getting:

if score[z] ==max IndexError: list index out of range

Edit: Traceback(most recent call last): File "squaresolver.py",line 156 in breed(bits:a,scores,p,bitsn) File "squaresolver.py", line 125, in breed if score[z] == maxx: IndexError: list index out of range

4
  • show the complete traceback, and identify the line it points to in your code Aug 29, 2016 at 0:25
  • Please provide a minimal reproducible example instead of dumping your entire code here and include the full stack trace which has helpful information such as exactly what line the error occurs on and how it was called. Aug 29, 2016 at 0:25
  • In general, this is probably caused by the numerous places in your code you use the error-prone method of trying to iterate over a list by indexes, instead of values directly. Don't: for i in range(len(x)): x[i]. Do: for thing in x: thing. Aug 29, 2016 at 0:26
  • thanks for your feedback, i know im posting it the wrong way ( I imagined it) this is my first time posting a question, ill edit it asap Aug 29, 2016 at 0:33

2 Answers 2

1

You don't need "score[z]" when you do "for z in score", z is not an index, is a value of the score list.

You can just do

if z == maxx
0

As you delete things in a list, you end up with index problems using range(len). If you have a list and then delete an item in it, you end up with a list whose length is now one less. This leads to IndexErrors as you try to access up to the original len(list).

Perhaps think of copying the original and working with that.

1
  • thanks!! It worked, sorry for being so newbie! and thanks again Aug 29, 2016 at 1:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.