I'm trying to make a program that removes certain elements from a group of lists if a certain condition happens, and duplicates them if a certain other condition happens. But I have the following problem: When the program is at iteration 50 out of 100, it flags IndexError and exits .
Here is the code snippet where I have the problem:
nnl_len = len(neuralNetworkList) # longitud de lista de objetos (siempre 100)
fitl_copy = fitness # lista de floats (siempre de longitud 100)
best_fitness_reproduced = 0
if worst_fitness < 0 and first_iteration == 0: # supongo que esto se
worst_fitness = 0 # puede ignorar
for i in range(nnl_len):
print(i)
if fitl_copy[i] < best_fitness: # LINEA EXACTA DEL ERROR <------------------
print("I DIED WITH A FITNESS OF ",fitness[i], ", BEING THE LIMIT ",best_fitness)
neuralNetworkList.pop(i)
x.pop(i)
y.pop(i)
fitness.pop(i)
colors.pop(i)
elif fitl_copy[i] == best_fitness and best_fitness_reproduced:
print("I DIED BECAUSE A TOP FITNESS CREATURE ALREADY REPRODUCED ",fitness[i])
neuralNetworkList.pop(i)
x.pop(i)
y.pop(i)
fitness.pop(i)
colors.pop(i)
else:
best_fitness_reproduced = 1
for j in range(99): # plus the mother is 100
print("I SURVIVED WITH A FITNESS OF ",fitness[i], ", BEING THE LIMIT ",best_fitness)
neuralNetworkList.append(neuralNetworkList[i])
if random.randint(1,3) == 1:
neuralNetworkList[i].mutate(i)
x.append(width)
y.append(height)
fitness.append(0)
newcolor = []
for h in range(3):
newcolor.append(round( colors[i][h]*random.choice((0.9, 1.1)) ))
colors.append(newcolor)
#except IndexError:
# pass
# print("I NEITHER DIED NOR REPRODUCED BECAUSE OF AN INDEX ERROR")
nnl_len = len(neuralNetworkList)
for i in range(nnl_len):
x[i] = width
y[i] = height
fitness[i] = 0
print("population after reproduction:", len(neuralNetworkList))
this is the traceback:
Traceback (most recent call last):
File "C:\Users\Ezequiel\Desktop\Archivos pavos\Sublime Text 3\pruebas_phyton.pyw", line 4921, in <module>
if fitl_copy[i] < best_fitness: # fitness[i] <= worst_fitness*4
IndexError: list index out of range
Thanks in advance
That's the clue; The problem occurs halfway through the process. This is a signal to try to remove from a list while iterating over it ; each time through the loop, it removes an item, so after 50 times it has
i == 50
and only 50 items still in the list, the index is out of bounds.Why did this happened? Good...
This does not make a copy of
fitness
; makes another name forfitness
.Accordingly, these two lines...
operates on the same list; and boom.
I think you should first try to rethink your algorithm. I guess you don't really need to want to pop all of the lists at all. I think it will be much easier if:
You may also benefit from using some kind of structured data for your creatures, instead of having parallel lists with all your attributes; and also by using list comprehensions and generators instead of for-loops.