I just started to program in python and I'm very interested in AI so I tried to make a simple genetic algorithm to find the word that I set as target but my population starts to become all the same and the program runs forever, can someone see what is my mistake?
import random
import string
import operator
population = []
scores = []
#Configs
target = ('Target')
length = len(target)
popsize = (100)
mutrate = (0.13)
itlimit = (1000)
#From https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch04s22.html
def random_pick(some_list, probabilities):
x = random.uniform(0, 1)
cumulative_probability = 0.0
for item, item_probability in zip(some_list, probabilities):
cumulative_probability += item_probability
if x < cumulative_probability: break
return item
#From http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
def rndstr():
return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(length))
def populate():
for p in range(0,popsize):
population.append(rndstr())
def evaluate():
for member in population:
scores.append(sum(map(operator.eq, member, target)))
def mate():
for index, pup in enumerate(population):
pai = random_pick(population,prob)
mae = random_pick(population,prob)
stp = 0
while pai == mae:
pai = random_pick(population,prob)
mae = random_pick(population,prob)
firstpart, secondpart = pai[:int(len(pai)/2)], mae[int(len(mae)/2):]
population[index] = firstpart + secondpart
def mutate():
for pop in population:
popl = list(pop)
for i in range(0, len(popl)):
if 1 == random.randint(1,mutrate*100):
popl[i] = random.choice(string.ascii_lowercase + string.ascii_uppercase)
''.join(popl)
populate()
print(population)
while target not in population and itlimit > 0:
itlimit = itlimit-1
print(itlimit)
evaluate()
prob = [float(i)/length for i in scores]
mate()
mutate()
print(population)