diff options
| author | Yuval Adam <yuv.adm@gmail.com> | 2011-09-28 14:41:47 +0300 |
|---|---|---|
| committer | Yuval Adam <yuv.adm@gmail.com> | 2011-09-28 14:41:47 +0300 |
| commit | ac413f38d249214d35701f2dbe934dc4ab77d52e (patch) | |
| tree | 548142b015ec989b6a7fa747758bbf3e82e41d90 /string_evolution/naive.py | |
| parent | adea2ea512f9f51786a8f7a9e6dcbe126745ebda (diff) | |
Diffstat (limited to 'string_evolution/naive.py')
| -rw-r--r-- | string_evolution/naive.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/string_evolution/naive.py b/string_evolution/naive.py new file mode 100644 index 0000000..4fbf52e --- /dev/null +++ b/string_evolution/naive.py @@ -0,0 +1,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 |
