from genetic import * """ Test code for the genetic module. String-based DNA @author Scott Hurring (scott at hurring dot com) @uri http://hurring.com/code/python/genetic/ @license GPL """ class MyCell(Cell): length = 4 name = "StringCell" alphabet = list("abcdefghijklmnopqrstuvwxyz") def init(self): self.dna = " " def randomize(self): """randomize my dna""" self.dna = "".join(random.sample(self.alphabet, self.length)) def clone(self): return MyCell() def get(self, i): return self.dna[i] def set(self, i, value): self.dna = self.dna[0:i] + value + self.dna[i+1:] def mutate(self, value): """mutate a piece of my dna by returning a random char""" return "".join(random.sample(self.alphabet, 1)) class MyFitnessJudge(object): """Judge fitness of a cell""" def fitness(self, cell): score = 0 chars = list(cell.dna) if chars[0] == "a": score += 25 if chars[1] == "s": score += 25 if chars[2] == "d": score += 25 if chars[3] == "f": score += 25 return score if __name__ == '__main__': # Number of generations to run numgens = 10 # Number of cells per generation numcells = 100 # Create Nature and tell it how to judge cells nature = Nature(MyFitnessJudge()) # Setup initial population population = nature.initial_population(MyCell, numcells) # Run simulation for a number of generations population = nature.run(population, numgens)