أخر الاخبار

Solve an example of a genetic algorithm using Python

 

ex/



sol//


1-

import random


# Initialize an empty list to store the population

population = []


# Generate a population of 10 individuals

for i in range(10):

    # Initialize an empty list to store the individual

    individual = []


    # Generate 7 digits for the individual

    for j in range(7):

        # Generate a random integer between 2 and 10 (inclusive)

        digit = random.randint(2, 10)

        individual.append(digit)


    # Add the individual to the population

    population.append(individual)


print(population)


2-

def one_max_objective(individual):

    # Initialize a variable to store the sum of the digits

    sum = 0


    # Iterate over the digits in the individual

    for digit in individual:

        # Add the digit to the sum

        sum += digit


    return sum


3-

def roulette_wheel_selection(population, fitness_scores):

    # Calculate the total fitness score of the population

    total_fitness = sum(fitness_scores)


    # Choose a random number between 0 and the total fitness

    choice_point = random.uniform(0, total_fitness)


    # Initialize a variable to store the current fitness

    current_fitness = 0


    # Select an individual based on the choice point

    for i, individual in enumerate(population):

        current_fitness += fitness_scores[i]

        if current_fitness > choice_point:

            return individual


4-

def swap_mutation(individual):

    # Choose two random indices to swap

    index1 = random.randint(0, len(individual) - 1)

    index2 = random.randint(0, len(individual) - 1)


    # Swap the values at the chosen indices

    individual[index1], individual[index2] = individual[index2], individual[index1]


    return individual

تعليقات



حجم الخط
+
16
-
تباعد السطور
+
2
-