applesauce

 avatar
unknown
plain_text
10 months ago
2.1 kB
5
Indexable
import random

# Define the target solution (Input solution)
TARGET_SOLUTION = "whats up, brothers?" 

# Define parameters
POPULATION_SIZE = 500
MUTATION_RATE = 0.05
GENERATIONS = 1000

# Generate an initial population of random individuals
def generate_population(size):
    return [''.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?') for _ in range(len(TARGET_SOLUTION))) for _ in range(size)]

# Evaluate the fitness of an individual (the closer to the target, the better)
def fitness(individual):
    return sum(1 for a, b in zip(individual, TARGET_SOLUTION) if a == b)

# Select individuals for the next generation based on their fitness
def select(population, num_parents):
    return sorted(population, key=fitness, reverse=True)[:num_parents]

# Crossover (combine) the genes of two parents to create a child
def crossover(parent1, parent2):
    crossover_point = random.randint(0, len(parent1) - 1)
    return parent1[:crossover_point] + parent2[crossover_point:]

# Mutate an individual by randomly changing some of its genes
def mutate(individual):
    return ''.join(c if random.random() > MUTATION_RATE else random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?') for c in individual)

# Main evolutionary algorithm
def evolve():
    population = generate_population(POPULATION_SIZE)

    for generation in range(GENERATIONS):
        parents = select(population, POPULATION_SIZE // 2)
        children = []

        while len(children) < POPULATION_SIZE:
            parent1, parent2 = random.sample(parents, 2)
            child = crossover(parent1, parent2)
            child = mutate(child)
            children.append(child)

        population = children

        best_individual = max(population, key=fitness)
        print("Generation {}, Best: {}, Fitness: {}".format(generation + 1, best_individual, fitness(best_individual)))

        if best_individual == TARGET_SOLUTION:
            print("Target solution found!")
            break

evolve()
Editor is loading...
Leave a Comment