Skip to content
The Chat Archive
mistral-7b-instruct· Mistral AI Arena Human Preference 55K

Python Code to "simulate biological creatures that evolve through natural selection"

  1. User

    Python Code to "simulate biological creatures that evolve through natural selection"

  2. Assistant

    Here's an example of Python code that simulates the evolution of a population of creatures through natural selection:

    import random
    
    class Creature:
        def __init__(self, genotype):
            self.genotype = genotype
    
        def fitness(self):
            # define the fitness of a creature based on its genotype
            if 'a' in self.genotype:
                return 1
            elif 'b' in self.genotype:
                return 0.5
            else:
                return 0.2
    
    class Population:
        def __init__(self, size, genotype_freq):
            self.size = size
            self.genotype_freq = genotype_freq
            self.population = [Creature(random.choices(['a', 'b'], k=5)) for _ in range(size)]
    
        def next_generation(self):
            offspring = []
            for _ in range(self.size):
                parent1 = random.choices(self, weights=lambda creature: creature.fitness())[0]
                parent2 = random.choices(self, weights=lambda creature: creature.fitness())[0]
                child = Creature(random.choices(['a', 'b'], k=5))
                child.genotype = random.choices(['a', 'b'], k=5)
                offspring.append(child)
            self.population = offspring
    
    # example usage
    pop_size = 100
    pop_freq = {'a': 0.2, 'b': 0.8}
    pop = Population(pop_size, pop_freq)
    for i in range(10):
        pop.next_generation()
        print(pop.genotype_freq)
    

    In this code, we define two classes: Creature and Population. The Creature class represents an individual creature with a genotype, which is a string of 'a' and 'b' characters. The fitness method defines how fit a creature is based on its genotype (in this case, 'a' is more fit than 'b'). The Population class represents a population of creatures with a certain size and a

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.