easythrees
easythrees

Reputation: 1650

Python: how to implement crossover of two integers?

I'm experimenting with a genetic search algorithm and after building the initial population at random, and then selecting the top two fittest entries, I need to 'mate' them (with some random mutation) to create 64 'children'. The crossover part, explained here:

https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3

seems easy to follow, but I can't seem to figure out how to implement it in Python. How can I implement this crossover of two integers?

Upvotes: 0

Views: 5207

Answers (2)

Jasmijn
Jasmijn

Reputation: 10452

def crossover(a, b, index):
    return b[:index] + a[index:], a[:index] + b[index:]

Should be quite a bit faster than James' solution, since this one lets Python do all the work!

Upvotes: 1

James H
James H

Reputation: 19

Here is a function called crossover that takes two parents and a crossover point. The parents should be lists of integers of the same length. The crossover point is the point before which genes get exchanged, as defined in the article that you linked to. It returns the two offspring of the parents.

def crossover(a, b, crossover_point):
    a1 = a[:]
    b1 = b[:]
    for i in range(crossover_point):
        a1[i], b1[i] = b1[i], a1[i]
    return [a1, b1]

And here is some code that demonstrates its usage. It creates a population consisting of two lists of length 10, one with only zeros, and the other with only ones. It crosses them over at point 4, and adds the children to the population.

def test_crossover():
    a = [0]*10
    b = [1]*10
    population = [a,b]
    population += crossover(a,b,4)
    return population

print (test_crossover())

The output of the above is:

[
   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
   [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
   [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
]

Upvotes: 0

Related Questions