# weasel program clone # by monkeyboy # should display "METHINHS IT IS LIKE A WEASEL" # Importing random classes import random # Defining variables aim = "METHINKS IT IS LIKE A WEASEL" #Defining the aim pop = [] i = 0 c = 0 mutrate = raw_input("Please set mutation rate (in %):") # sets mutation rate in % mutrate = int(mutrate) size = raw_input("Please enter offspring size:") # setting offspring size size = int(size) def umwandel(var): # Converts a list into a string a = "" c = 0 while c < 28: a = a + (var[c]) c = c + 1 return a def convert(var): # Converts a string into a list a = [] c = 0 while c < 28: a += [var[c]] c = c + 1 return a def zufall(): # Generates a random letter alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " random.seed() a = random.randrange(0, 27, 1) b = alphabet[a] return b def mutate(var,mutrate): # mutates each letters in a string of 28 elements with a (mutrate) % likelihood c = 0 while c < 28: random.seed() a = random.randrange(1,100,1) if a <= mutrate: b = zufall() var = convert(var) var[c] = b var = umwandel(var) c = c + 1 return var def fittnes(var1,var2): # Compares the level of similarity between 2 strings of 28 elements c = 0 # The result is an integer i = 0 while c < 28: if var1[c] == var2[c]: i = i + 1 c = c + 1 return i def population(var,size): # Generates a list of strings with (size) random elements c = 1 b = [] while c <= size: b += [mutate(var,100)] c = c +1 return b def selection(aim,pop,size): # Selects the element of a list which has the most similarities with a given aim c = 0 a = "" f = 0 while c <= size-1: b = pop[c] i = fittnes(aim,b) if i > f: f = i a = pop[c] c = c + 1 return a,f def offspring(mother,mutrate,size): # Generates a list of mutations from 'mother' with 'size' elements c = 1 children = [] while c <= size: children += [mutate(mother,mutrate)] c = c + 1 return children # Main program pop = population(aim,size) # Setting a starting population mother = selection(aim,pop,size) # picks the element from the starting population with the most similarities to the aim print "Generation " + str(c) print "Best fit:" + mother[0] + " Similarities:" + str(mother[1]) print while i < 28: # loop will run till a complete match c = c + 1 # counts the generations pop = offspring(mother[0],mutrate,size) # a new generation will be generated from the last run's 'best fit mother = selection(aim,pop,size) # this generation's 'best fit' print "Generation " + str(c) print "Best fit:" + mother[0] + " Similarities:" + str(mother[1]) print i = mother[1]