-
Notifications
You must be signed in to change notification settings - Fork 0
/
genetichelloworld.py
76 lines (61 loc) · 2.04 KB
/
genetichelloworld.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import math
from random import random
MUTATE_RATE = 0.01;
BREED_RATE = 0.75;
POPULATION_SIZE = 1000;
TARGET = 'Hello, World';
def generateCharacter():
return chr(math.floor((random() * 94) + 32))
def selectParent(elders, totalScore):
selection = random() * totalScore
sum = 0
for e in elders:
sum += e['score']
if selection <= sum:
return e
def generatePopulation():
p = []
for i in range(POPULATION_SIZE):
x = ''
for c in TARGET:
x += generateCharacter()
p.append(x)
return p
def checkFitness(x):
r = {'value': x, 'score': 0}
for i in range(len(TARGET)):
if x[i] == TARGET[i]:
r['score'] += 1
return r
def breed(p1, p2):
c = ''
for i in range(len(TARGET)):
if random() < MUTATE_RATE:
c += generateCharacter()
else:
if random() < 0.5:
c += p1[i]
else:
c += p2[i]
return c
population = generatePopulation()
generation = 0
print('Using a population of size {}'.format(POPULATION_SIZE))
print('Regenerating {:%} of the population per generation'.format(BREED_RATE))
print('{:%} chance of mutation for each chromosome'.format(MUTATE_RATE))
while population[0] != TARGET:
generation += 1
results = list(map(checkFitness, population))
results.sort(key=lambda x: x['score'], reverse=True)
if results[0]['value'] != TARGET:
elders = results[0:int(POPULATION_SIZE * (1 - BREED_RATE))]
population = []
[population.append(person) for person in map(lambda x: x['value'], elders)]
totalScore = sum([n['score'] for n in elders])
for i in range(int(POPULATION_SIZE * BREED_RATE)):
p1 = selectParent(elders, totalScore)['value']
p2 = selectParent(elders, totalScore)['value']
population.append(breed(p1, p2))
else:
population = list(map(lambda x: x['value'], results))
print('Generation {}: {}, score: {}'.format(generation, results[0]['value'], results[0]['score']))