|
| 1 | +import random |
| 2 | + |
| 3 | +# Define the target string (the goal of the genetic algorithm) |
| 4 | +target_string = "Hello, World!" |
| 5 | + |
| 6 | +# Function to generate a random string of the same length as the target |
| 7 | +def generate_random_string(length): |
| 8 | + return ''.join(random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,.!?") for _ in range(length)) |
| 9 | + |
| 10 | +# Function to calculate the fitness of an individual (string) |
| 11 | +def calculate_fitness(individual): |
| 12 | + return sum(1 for i, j in zip(individual, target_string) if i == j) |
| 13 | + |
| 14 | +# Function to perform selection (tournament selection) |
| 15 | +def selection(population): |
| 16 | + tournament_size = 3 |
| 17 | + selected = [random.choice(population) for _ in range(tournament_size)] |
| 18 | + return max(selected, key=calculate_fitness) |
| 19 | + |
| 20 | +# Function to perform crossover (single-point crossover) |
| 21 | +def crossover(parent1, parent2): |
| 22 | + point = random.randint(1, len(parent1) - 1) |
| 23 | + child = parent1[:point] + parent2[point:] |
| 24 | + return child |
| 25 | + |
| 26 | +# Function to perform mutation (random character mutation) |
| 27 | +def mutation(individual, mutation_rate): |
| 28 | + return ''.join( |
| 29 | + random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,.!?") |
| 30 | + if random.random() < mutation_rate else char |
| 31 | + for char in individual |
| 32 | + ) |
| 33 | + |
| 34 | +# Main genetic algorithm loop |
| 35 | +population_size = 100 |
| 36 | +mutation_rate = 0.01 |
| 37 | + |
| 38 | +population = [generate_random_string(len(target_string)) for _ in range(population_size)] |
| 39 | + |
| 40 | +generation = 1 |
| 41 | +while True: |
| 42 | + population = sorted(population, key=calculate_fitness, reverse=True) |
| 43 | + best_individual = population[0] |
| 44 | + |
| 45 | + if best_individual == target_string: |
| 46 | + break |
| 47 | + |
| 48 | + new_population = [best_individual] |
| 49 | + |
| 50 | + while len(new_population) < population_size: |
| 51 | + parent1 = selection(population) |
| 52 | + parent2 = selection(population) |
| 53 | + child = crossover(parent1, parent2) |
| 54 | + child = mutation(child, mutation_rate) |
| 55 | + new_population.append(child) |
| 56 | + |
| 57 | + population = new_population |
| 58 | + generation += 1 |
| 59 | + |
| 60 | + if generation % 10 == 0: |
| 61 | + print(f"Generation {generation}: {best_individual} (Fitness: {calculate_fitness(best_individual)})") |
| 62 | + |
| 63 | +print(f"Generation {generation}: {best_individual} (Fitness: {calculate_fitness(best_individual)})") |
| 64 | +print("Genetic algorithm completed!") |
0 commit comments