-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopulation.py
52 lines (36 loc) · 1.44 KB
/
population.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
"""
Population of random solutions. Mutates current population to generate the next.
The MUTATION_PROBABILITY parameter controls the proportion of individuals in the
population that are mutated (the rest is copied without changes).
Prints best, worst and median fitness of individuals in the final population.
QUESTION: does it work? what is missing?
"""
import string
import random
TARGET = "CHARLES DARWIN"
CHARACTERS = string.ascii_uppercase + " "
GENERATIONS = 50
POPULATION_SIZE = 100
MUTATION_PROBABILITY = 0.001
MUTATION_RATE = 0.1
def evaluate(solution):
return sum(1 for s,t in zip(solution, TARGET) if s != t)
def init():
return [random.choice(CHARACTERS) for i in range(len(TARGET))]
def mutate(solution):
f = lambda x: random.choice(CHARACTERS) if random.random() < MUTATION_RATE else x
return [f(x) for x in solution]
def variate(population):
for i in range(len(population)):
if random.random() < MUTATION_PROBABILITY:
population[i] = mutate(population[i])
return population
population = [init() for i in range(POPULATION_SIZE)]
fitnesses = [evaluate(individual) for individual in population]
for i in range(GENERATIONS):
population = variate(population)
fitnesses = [evaluate(individual) for individual in population]
fitnesses.sort()
params = fitnesses[0], fitnesses[-1], fitnesses[POPULATION_SIZE // 2]
print("best={0}, worst={1}, median={2}".format(*params))