GA in python

Here is a sample Genetic Algorithm (GA) program written in python. There are many ways to
create a GA program, this one is probably one of the simplest.

The code is self explanatory. First we create a population of entities and assign a random
chromosome to each entity. Then we apply a fitness function to each entity. This part is
application specific, in this example we just count the number of ones in the chromosome.

The roulette function selects a pair of entities, probability of being selected depends on
how close the fitness function is to the target (or the designated solution). At this point one
of three things happen to each pair selected:

Crossover: at a random location on the chromosome, we swap the chromosomes.

Mutation: we flip a bit at a random location on the chromosome.

No change: the pair moves on to the next generation unchanged.

This example is pretty lame and so the idea of genes do not apply. In a real example, the bit
combinations would represent alternate solutions to the problem at hand. When one of the
entities get to the target, its chromosome represents the solution to the problem.

Genetic Algorithms are very efficient search algorithms. Here is the program: