Open links in new tab
    • Work Report
    • Email
    • Rewrite
    • Speech
    • Title Generator
    • Smart Reply
    • Poem
    • Essay
    • Joke
    • Instagram Post
    • X Post
    • Facebook Post
    • Story
    • Cover Letter
    • Resume
    • Job Description
    • Recommendation Letter
    • Resignation Letter
    • Invitation Letter
    • Greeting Message
    • Try more templates
  1. A genetic algorithm (GA) is a search heuristic inspired by natural selection. Below is an implementation of a GA in Python to evolve a binary string where all bits are set to 1.

    Steps to Implement the Genetic Algorithm

    1. Initialize Population: Create a random population of binary strings.

    2. Fitness Function: Evaluate how close each individual is to the target (all ones).

    3. Selection: Choose the fittest individuals for reproduction.

    4. Crossover: Combine parents to produce offspring.

    5. Mutation: Introduce random changes to maintain diversity.

    6. Repeat: Iterate until the target is achieved or a maximum number of generations is reached.

    Python Implementation

    import random

    # Parameters
    POPULATION_SIZE = 20
    CHROMOSOME_LENGTH = 10
    MUTATION_RATE = 0.1
    GENERATIONS = 100

    # Generate initial population
    def initialize_population():
    return [[random.randint(0, 1) for _ in range(CHROMOSOME_LENGTH)] for _ in range(POPULATION_SIZE)]

    # Fitness function: Count the number of ones
    def fitness(individual):
    return sum(individual)

    # Selection: Roulette Wheel Selection
    def select(population, fitnesses):
    total_fitness = sum(fitnesses)
    probabilities = [f / total_fitness for f in fitnesses]
    return population[random.choices(range(len(population)), probabilities)[0]]

    # Crossover: Single-point crossover
    def crossover(parent1, parent2):
    point = random.randint(1, CHROMOSOME_LENGTH - 1)
    return parent1[:point] + parent2[point:], parent2[:point] + parent1[point:]

    # Mutation: Flip bits with a certain probability
    def mutate(individual):
    return [bit if random.random() > MUTATION_RATE else 1 - bit for bit in individual]

    # Main Genetic Algorithm Loop
    def genetic_algorithm():
    population = initialize_population()
    for generation in range(GENERATIONS):
    fitnesses = [fitness(ind) for ind in population]
    if max(fitnesses) == CHROMOSOME_LENGTH:
    print(f"Solution found in generation {generation}")
    break

    new_population = []
    for _ in range(POPULATION_SIZE // 2):
    parent1 = select(population, fitnesses)
    parent2 = select(population, fitnesses)
    child1, child2 = crossover(parent1, parent2)
    new_population.extend([mutate(child1), mutate(child2)])

    population = new_population

    # Print the best solution
    best_individual = max(population, key=fitness)
    print("Best Individual:", best_individual)
    print("Fitness:", fitness(best_individual))

    # Run the algorithm
    genetic_algorithm()
    Copied!
    Feedback
  2. Genetic Algorithm: Complete Guide With Python …

    Jul 29, 2024 · Now that we have a good handle on what genetic algorithms are and generally how they work, let’s build our own genetic algorithm to solve a simple …

  3. PyGAD - Python Genetic Algorithm! — PyGAD 3.5.0 …

    Currently, PyGAD supports building and training (using genetic algorithm) artificial neural networks for classification problems. The library is under active …

  4. Simple Genetic Algorithm From Scratch in Python

    Genetic algorithm is a stochastic optimization algorithm inspired by evolution. How to implement the genetic algorithm from scratch in Python. How to apply the …

  5. PyGAD: Genetic Algorithm in Python - GitHub

    • PyGAD is an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizin…
      Check documentation of the PyGAD.
    • PyGAD supports different types of crossover, mutation, and parent selection. PyGAD allows different ty…
      The library is under active development and more features are added regularly. If you want a feature to be supported, please check the Contact Us section to send a request.
    See more on github.com
  6. Genetic Algorithms With Scikit-Learn In Python

    • See More

    Jul 8, 2025 · Learn how to implement genetic algorithms using Scikit-Learn in Python with this practical guide. Optimize machine learning models with evolutionary strategies.

  7. How to Build a Genetic Algorithm from Scratch in Python

    Aug 30, 2024 · In this article, I will show the reader how to build their own Genetic Algorithm with Python and apply it to a real-world use case. Why use a Genetic …

  8. Genetic Algorithm in Python - Ander Fernández

    In this post you have been able to learn what a genetic algorithm is, how it works and how to use it easily in Python, both for optimization models and for …

  9. Genetic Algorithm in Python: A Comprehensive Guide

    Mar 18, 2025 · This blog will walk you through the fundamental concepts, usage methods, common practices, and best practices of genetic algorithms in Python.

  10. Building a Genetic Algorithm from Scratch in Python

    Nov 16, 2024 · Master the implementation of genetic algorithms in Python with this comprehensive guide, including step-by-step explanations and code examples.

  11. pygad · PyPI

    Jul 8, 2025 · PyGAD is an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizing machine learning algorithms. It supports Keras …