-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenetic_algorithm_chapter_1.py
51 lines (41 loc) · 1.39 KB
/
Genetic_algorithm_chapter_1.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
import random
import datetime
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
target = "Hello World!"
random.seed()
startTime = datetime.datetime.now()
#generate a random string from the gene set.
def generate_parent(length):
genes = []
while len(genes) < length:
sampleSize = min(length-len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
return ''.join(genes)
bestParent = generate_parent(len(target))
def get_fitness(guess):
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)
bestFitness = get_fitness(bestParent)
def mutate(parent):
index = random.randrange(0, len(parent))
childGenes = list(parent)
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate \
if newGene == childGenes[index] \
else newGene
return ''.join(childGenes)
def display(guess):
timeDiff = datetime.datetime.now() - startTime
fitness = get_fitness(guess)
print("{0}\t{1}\t{2}".format(guess, fitness, str(timeDiff)))
display(bestParent)
while True:
child = mutate(bestParent)
childFitness = get_fitness(child)
if bestFitness >= childFitness:
continue
display(child)
if childFitness >= len(bestParent):
break
bestFitness = childFitness
bestParent = child