"Survival of the fittest string." — Charles Darwin, probably, if he coded in Python.
A genetic algorithm that evolves a random population of strings toward a target phrase. No brains required — just selection pressure and a little chaos.
1500 random strings are generated, each the same length as the target. Think of it as hiring 1500 monkeys and hoping one of them types Shakespeare.
Each string is scored by counting how many characters match the target at the correct position. A score of len(target) means we're done.
fitness(individual) = Σ (individual[i] == target[i])
Parents are selected probabilistically — fitter individuals get a bigger slice of the wheel. The weak still get picked sometimes. Democracy, but rigged.
P(individual) = fitness(individual) / Σ fitness(all)
Cumulative probabilities are built so a single random() roll picks a parent in O(n).
Two parents produce two children. For each gene position, a coin flip decides which parent donates. CROSSOVER_PROBABILITY = 1 means a swap always happens on a heads flip.
bit = random(0,1)
child1[i] = parentB[i] if bit == 1 else parentA[i]
child2[i] = parentA[i] if bit == 1 else parentB[i]
Each gene has a 1% chance of being replaced with a random character from the gene pool. This prevents the population from converging too early and getting stuck in a local optimum — the genetic equivalent of "have you tried turning it off and on again?"
| Parameter | Value | What it does |
|---|---|---|
POPULATION_POOL_SIZE | 1500 | More individuals = more diversity, more compute |
MUTATION_RATE | 0.01 | Too high → chaos. Too low → stagnation. 1% is the sweet spot |
CROSSOVER_PROBABILITY | 1 | Always swap on a 1 bit flip (uniform crossover) |
NUMBER_OF_INDIVIDUAL_PARENTS | 2 | Classic sexual reproduction. Nothing weird |
GENE_POOL | letters + digits + punctuation + space | The alphabet soup your strings are made of |
This is a search algorithm disguised as biology. The algorithm never "knows" what the target is — it only knows a fitness score. Given enough generations and selection pressure, it converges. The same principle scales to neural network weight optimization, game AI, and scheduling problems.
The target string is found when best == target. No gradient. No backprop. Just vibes and natural selection.
python main.pyWatch your population crawl toward enlightenment, one generation at a time.