Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- from collections import namedtuple
- def evolve(initialise_population_f, fitness_f, breed_f, num_generations=100):
- """
- initialise_population: Returns an initial population represented as a list
- fitness_f : Fitness function
- breed_f : Takes two elements and breeds them, possibly introducing mutations
- num_generations : Number of generations to run the evolver for
- """
- Individual = namedtuple("Individual", ["fitness", "gene"])
- population = [Individual(fitness_f(x), x) for x in initialise_population_f()]
- pop_size = len(population)
- def rand_index():
- return max(pop_size - 1, int(pop_size * random.triangular(0, 1, 1)))
- for generation in range(num_generations):
- new_population = []
- population.sort()
- for i in range(pop_size):
- index1 = rand_index()
- index2 = rand_index()
- new_indiv = breed_f(population[index1].gene, population[index2].gene)
- new_population.append(Individual(fitness_f(new_indiv), new_indiv))
- population = new_population
- population.sort()
- return population[-1]
- alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ, !"
- def rand_string(n, alphabet):
- return "".join([random.choice(alphabet) for i in range(n)])
- def initialise_population():
- return [rand_string(13, alphabet) for i in range(1000)]
- def fitness_function(string):
- return sum((1 if string[i] == "Hello, World!"[i] else 0) for i in range(len(string)))
- def breed(string1, string2):
- global alphabet
- index = random.randint(0, len(string1) - 1)
- child = string1[:index] + string2[index:]
- if random.random() < 0.1:
- mutation_index = random.randint(0, len(child) - 1)
- child = child[:mutation_index] + random.choice(alphabet) + child[mutation_index+1:]
- return child
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement