I was writing a simple genetic program to test out the process, but got the following error:
Traceback (most recent call last):
File "evolution.py", line 43, in <module>
nextgen += test[operator.indexOf(list(fits), m+chance)]
TypeError: iteration over non-sequence
on the code:
#!/usr/bin/env python
import random
import operator
mutationchance = 0.01
simtime = 1000
# quadratic optimizer
class Organism:
def __init__(self, x):
self.x = x
self.a = 1
self.b = 2
self.c = 3
self.epsilon = 0.01
def fitness(self):
return self.a*(self.x**2) + self.b*(self.x) + self.c
def mutate(self):
self.x += random.random() - 0.5
def describe(self):
return self.x
def condmutate(org, chance):
if random.random() <= chance:
org.mutate()
return org
test = [Organism(i) for i in range(-10, 10)]
generation = 0
while generation < simtime:
fits = [test[i].fitness() for i in range(0, len(test) - 1)]
sumf = sum(fits)
i = 0
nextgen = list()
while i < len(fits) / 2:
chance = random.random() * sumf
j = 0
shg = [fits[i] - chance for i in range(0, len(test) - 1)]
m = min(shg)
nextgen += test[operator.indexOf(list(fits), m+chance)]
nextgen += test[operator.indexOf(list(fits), m+chance)]
test = [condmutate(test[i], mutationchance) for i in range(0, len(nextgen) - 1)]
generation += 1
print "result: ", max([test[i].describe() for i in range(0, len(test) - 1)])
I am new to Python, so it may just be a newbie mistake.
printstatements (orprint()functions, depending on your version) in front of the failing statement to print out the various variables to be sure of the types. You could try that -- addprintstatements to show what the values offits,test,mandchanceare.