Ich wollte den Algorithmus von http://scienceblogs.de/diaxs-rake/2010/ ... in-python/ selber programmieren und habe folgendes geschrieben:
Code: Alles auswählen
#! /usr/bin/python
# -*- coding: utf-8 -*-
#Erstes Programm zur Genetischen Programmierung
from string import uppercase
from random import random
TARGET = "DUHASTESGESCHAFFT"
LETTERS = uppercase
POPULATION = 200
p_dict = {}
c_dict = {}
fittness = {}
list_pop = []
count = 0
generation = 1
mother = 0
father = 0
ERB_VALUE = 0.40
MUT_VALUE = 0.45
stri = ""
cache = ""
cache2 = ""
#Parent-Generation erstellen
for i in range(POPULATION):
for c in range(len(TARGET)):
stri += LETTERS[int(random() * 26)]
p_dict[i] = stri
stri = ""
while True:
#Fitness zu der Parent-Generation
for c in p_dict:
for i in range(len(TARGET)):
if p_dict[c][i] == TARGET[i]:
count += 1
fittness[c] = count
count = 0
#Liste für Zufallsauswahl
list_pop += p_dict.keys()
for i in fittness:
list_pop += list(str(i)) * fittness[i]
#Child-Generation erstellen
for i in range(POPULATION):
mother = int(list_pop[int(random() * len(list_pop))])
father = int(list_pop[int(random() * len(list_pop))])
cache = p_dict[mother]
cache2 = p_dict[father]
if random() > 0.5:
c_dict[i] = cache[0:int(ERB_VALUE * len(TARGET))] + cache2[int(ERB_VALUE * len(TARGET)):]
elif random() < 0.5:
c_dict[i] = cache2[0:int(ERB_VALUE * len(p_dict[father]))] + cache[int(ERB_VALUE * len(p_dict[mother])):]
#Mutationen
for c in c_dict:
for s in range(len(c_dict[c])):
if random() > MUT_VALUE:
c_dict[c] = c_dict[c][:s - 1] + LETTERS[int(random() * 26)] + c_dict[c][s:]
if c_dict[c] == TARGET:
print "Lösung gefunden in der %dten Generation: %s" % (generation, c_dict[c])
break
generation += 1
p_dict = c_dict
c_dict = {}
print "End"
Bis jetzt weiß ich nur, dass nach ein paar Runden die die For-Schleife gemacht hat, ein Eintrag in dem Dictionary gelöscht wird.
Soweit ich weiß, ist die Anzahl dieser Runden immer unterschiedlich.
Sieht da jemand einen Fehler?
Schonmal Danke im vorraus.