Auto Byte

Science AI

利用达尔文的理论学习遗传算法

选择一个适应度函数

``fitness score = (number of char correct) / (total number of char)``

``````def fitness (password, test_word):

print("taille incompatible")
return
else:
score = 0
i = 0
score+=1
i+=1
return score * 100 / len(password)
``````

创建第一个种群

``````import random

def generateAWord (length):
i = 0
result = ""
while i < length:
letter = chr(97 + int(26 * random.random()))
result += letter
i +=1
return result

population = []
i = 0
while i < sizePopulation:
i+=1
return population``````

从一代到下一代

育种者选择

``````import operator
import random

populationPerf = {}
for individual in population:
return sorted(populationPerf.items(), key = operator.itemgetter(1), reverse=True)

def selectFromPopulation(populationSorted, best_sample, lucky_few):
nextGeneration = []
for i in range(best_sample):
nextGeneration.append(populationSorted[i][0])
for i in range(lucky_few):
nextGeneration.append(random.choice(populationSorted)[0])
random.shuffle(nextGeneration)
return nextGeneration``````

繁衍

``````import random

def createChild(individual1, individual2):
child = ""
for i in range(len(individual1)):
if (int(100 * random.random()) < 50):
child += individual1[i]
else:
child += individual2[i]
return child

def createChildren(breeders, number_of_child):
nextPopulation = []
for i in range(len(breeders)/2):
for j in range(number_of_child):
nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i]))
return nextPopulation``````

突变

``````import random

def mutateWord(word):
index_modification = int(random.random() * len(word))
if (index_modification == 0):
word = chr(97 + int(26 * random.random())) + word[1:]
else:
word = word[:index_modification] + chr(97 + int(26 * random.random())) + word[index_modification+1:]
return word

def mutatePopulation(population, chance_of_mutation):
for i in range(len(population)):
if random.random() * 100 < chance_of_mutation:
population[i] = mutateWord(population[i])
return population``````