Jennifer Hallinan wrote: > Hi, > > I have a mutate function for a genetic algorithm which is giving me > odd results. I suspect I'm missing somthing really simple, so I'd be > grateful for any suggestions. Basically, when I comment out the line > which is commented out below, it works fine (although of course it > doesn't change the genome). When I uncomment it gen[letter] > automagically gets the value base in the print statements, before the > assignment has been made. And it still doesn't update the genome. > Genome is a string of integers in the range 0- 3, hence the > conversion. > > def Mutate(self, mrate): > g = Random(rseed) > # If no mutation rate specified, use 1 per genome > if mrate == -1: > mrate = 1.0/len(self.genome) > print "mrate is ", mrate > > print "original genome: " > print self.genome > # convert genome to a list > gen = [ord(letter)-48 for letter in self.genome] > > for letter in range(len(gen)): > rnum = g.random() > if rnum < mrate: > base = g.randint(0,3) > print "base is ", base > print "pos ", letter, gen[letter], " to ", base > # gen[letter] = base > > # convert list back to a string > self.genome = ''.join([str(x) for x in gen]) > print "final genome" > print self.genome > [...] > > Thanks, > > Jen
Jen how about storing the genome data as a list, then converting to a string if needs be? import random class Genome(object): def __init__(self, genome): self.genome = list(genome) self.mrate = 1.0/len(genome) def __str__(self): return ''.join(self.genome) def Mutate(self): for i in range(len(self.genome)): if random.random() < self.mrate: self.genome[i] = str(random.randint(0,2)) print G = Genome( '10021010212021110' ) print G G.Mutate() print G G.mrate = 0.8 G.Mutate() print G Gerard -- http://mail.python.org/mailman/listinfo/python-list