summaryrefslogtreecommitdiff
path: root/string_evolution/naive.py
blob: 4fbf52ef0b0727654e03841260c23de17903f7b7 (plain)
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
### http://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/

import random
from time import sleep

source = "jiKnp4bqpmAbp"
target = "Hello, World!"

def fitness(source, target):
    fitval = 0
    for i in range(0, len(source)):
        fitval += (ord(target[i]) - ord(source[i])) ** 2
    return(fitval)

def mutate(source):
    charpos = random.randint(0, len(source) - 1)
    parts = list(source)
    parts[charpos] = chr(ord(parts[charpos]) + random.randint(-1,1))
    return(''.join(parts))

fitval = fitness(source, target)
i = 0
while True:
    i += 1
    m = mutate(source)
    fitval_m = fitness(m, target)
    if fitval_m < fitval:
        fitval = fitval_m
        source = m
        print "%5i %5i %14s" % (i, fitval_m, m)
        sleep(0.1)
    if fitval == 0:
        break