Last active
September 22, 2021 01:36
-
-
Save joaopedro-fg/d6a5209c6dd836d0561ec3fb79bcbc33 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import string | |
| import random | |
| import matplotlib.pyplot as plt | |
| target = 'METHINKS IT IS LIKE A WEASEL' | |
| letters = string.ascii_uppercase | |
| letters = list(letters) | |
| letters.append(' ') | |
| def retornar_copia(setenca): | |
| return setenca[:] | |
| def mutacao(letter): | |
| chance = random.randint(1,100) | |
| if chance<=5: | |
| return random.choice(letters) | |
| else: | |
| return letter | |
| def mutacao_palavra(word): | |
| return ''.join(list(map(mutacao,word))) | |
| def string_similarity(a): | |
| return sum (a[i] == target[i] for i in range(len(a))) | |
| def generate_random_string(n): | |
| return ''.join(random.choice(letters) for i in range(n)) | |
| initial_string = generate_random_string(28) | |
| tries=0 | |
| fitness = [] | |
| while string_similarity(initial_string) != 28: | |
| lista = [retornar_copia(initial_string) for i in range(100)] | |
| lista= list(map(mutacao_palavra,lista)) | |
| lista_scores = list(map(string_similarity,lista)) | |
| max_value = max(lista_scores) | |
| max_index = lista_scores.index(max_value) | |
| initial_string=lista[max_index] | |
| tries += 1 | |
| fitness.append(max_value/28) | |
| print(tries) | |
| plt.plot(fitness) | |
| plt.ylabel('Porcentagem de Caracteres Corretos') | |
| plt.xlabel('Geração') | |
| plt.savefig('genetic.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment