Created
March 18, 2023 11:30
-
-
Save siu-issiki/842520926fddcdfe93f6d1166f790c0d to your computer and use it in GitHub Desktop.
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
import random | |
import string | |
TARGET = "Hello, World!" | |
POPULATION_SIZE = 100 | |
MUTATION_RATE = 0.05 | |
GENERATIONS = 1000 | |
INITIAL_INDIVIDUAL = "Cr3@tiv3_#ode" | |
def generate_individual(): | |
return INITIAL_INDIVIDUAL | |
def calculate_fitness(individual): | |
return sum(1 for a, b in zip(individual, TARGET) if a == b) / len(TARGET) | |
def select(population, fitnesses): | |
return random.choices(population, weights=fitnesses, k=2) | |
def crossover(parent1, parent2): | |
crossover_point = random.randint(0, len(TARGET)) | |
return ( | |
parent1[:crossover_point] + parent2[crossover_point:], | |
parent2[:crossover_point] + parent1[crossover_point:] | |
) | |
def mutate(individual): | |
chars = string.ascii_letters + string.punctuation + string.whitespace | |
return ''.join( | |
c if random.random() > MUTATION_RATE else random.choice(chars) | |
for c in individual | |
) | |
population = [generate_individual() for _ in range(POPULATION_SIZE)] | |
for generation in range(GENERATIONS): | |
fitnesses = [calculate_fitness(individual) for individual in population] | |
new_population = [] | |
for _ in range(POPULATION_SIZE // 2): | |
parent1, parent2 = select(population, fitnesses) | |
child1, child2 = crossover(parent1, parent2) | |
new_population.extend([mutate(child1), mutate(child2)]) | |
population = new_population | |
best_individual = max(population, key=calculate_fitness) | |
print(f"Generation {generation + 1}, best individual: {best_individual}, " | |
f"fitness: {calculate_fitness(best_individual)}") | |
if best_individual == TARGET: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ python3 main.py