Created
June 17, 2017 07:34
-
-
Save CuyiGuaton/b95088b54cee1bc014d940a514d57833 to your computer and use it in GitHub Desktop.
Hello world with Genetic algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Hello world with Genetic algorithm | |
""" | |
import random | |
#Generate random string with same lenght that target | |
def initialization(target, letters): | |
string = [] | |
string.extend(random.sample(letters, len(target))) | |
return ''.join(string) | |
#Return a sum with the corrects letters of target | |
def fitness(string, target): | |
sum = 0 | |
for i in range(len(string)): | |
if(string[i] == target[i]): | |
sum +=1 | |
return sum | |
#Add an random letter from letters to string | |
def mutate(parent, letters): | |
index = random.randrange(0, len(parent)) | |
aux = list(parent) | |
letter = random.sample(letters, 1) | |
aux[index] = letter[0] | |
return ''.join(aux) | |
def main(): | |
letters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." | |
target = "Hello World!" | |
parent = initialization(target, letters) | |
fit = fitness(parent, target) | |
while target != parent: | |
child = mutate(parent, letters) | |
childFit = fitness(child, target) | |
if fit >= childFit: | |
continue | |
print(child) | |
parent = child | |
fit = childFit | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment