This is based on a very similar question I asked, found here.
The intent of this program is to start with a set number of random strings of zeros and ones, and eventually evolve them to find one specific string ('111111'
).
It fulfils its purpose, but what do you think, and how can I improve it?
import random as r
import operator
import time
import os
target = '111111'
class String(object):
def __init__(self, chromo):
self.chromo = chromo
self.fitness = 5
self.age = 0
def Fitness(string):
for char in string.chromo:
if char == '1':
string.fitness += 1
else:
pass
def SelectParents(strings):
parents = []
parents.append(max(strings, key=operator.attrgetter('fitness')))
strings.remove(parents[0])
parents.append(max(strings, key=operator.attrgetter('fitness')))
strings.append(parents[0])
return parents
def PartStringRand():
string_complete = ''
for _ in range(4):
rand = r.randint(0, 1)
string_element = str(rand)
string_complete = ''.join([string_complete, string_element])
return string_complete
def CreateChild(strings, parents):
for children in range(2):
string_complete = PartStringRand()
string_complete += (parents[0].chromo[r.randint(0, 5)] + parents[1].chromo[r.randint(0, 5)])
child = String(string_complete)
strings.append(child)
def KillOld(strings):
for _ in strings:
if _.age > 2:
strings.remove(_)
#First strings
strings = []
for _ in range(5):
string_complete = ''
for _ in range(6):
rand = r.randint(0, 1)
string_element = str(rand)
string_complete = ''.join([string_complete, string_element])
string = String(string_complete)
strings.append(string)
if string.chromo == "111111":
strings.remove(string)
for string in strings:
print string.chromo
raw_input()
#Start incremental mutation
c = 0
for _ in range(5000000):
#os.system("cls")
for string in strings:
Fitness(string)
parents = SelectParents(strings)
CreateChild(strings, parents)
for organism in strings:
organism.age += 1
print organism.chromo
if organism.chromo == '111111':
print "::...Successfully evolved specifc string '111111' from random strings...::"
time.sleep(4)
sys.exit()
KillOld(strings)
c += 1
print "Generation: %s" %c
#time.sleep(0.3)