IND_LEN = 25 MAX_GEN = 100 POP_SIZE = 50 import random def create_individual(): return [random.randint(0,1) for _ in range(IND_LEN)] def create_random_population(): return [create_individual() for _ in range(POP_SIZE)] def fitness(ind): return sum(ind) def select(inds, fits): return random.choices(inds, fits, k=POP_SIZE) def cross(p1, p2): point = random.randint(0, len(p1)-1) o1 = p1[:point] + p2[point:] o2 = p2[:point] + p1[point:] return o1, o2 def crossover(pool): off = [] for p1, p2 in zip(pool[::2], pool[1::2]): o1, o2 = cross(p1, p2) off += [o1, o2] return off def mutation(pool): return [mutate(p) for p in pool] def mutate(p1): o = [] for i in p1: if random.random() < 0.01: o.append(1-i) else: o.append(i) return o def mate(pool): o1 = crossover(pool) return mutation(o1) def evolutionary_algorithm(fitness): log = [] pop = create_random_population() for G in range(MAX_GEN): fits = [fitness(p) for p in pop] log.append((max(fits), sum(fits)/len(fits))) mating_pool = select(pop, fits) offspring = mate(mating_pool) pop = offspring[:] return pop, log if __name__ == '__main__': import pprint res, log = evolutionary_algorithm(fitness) fits = [fitness(r) for r in res] pprint.pprint(list(zip(res, fits))) pprint.pprint(log) import matplotlib.pyplot as plt plt.plot([l[0] for l in log]) plt.plot([l[1] for l in log]) plt.show()