SEXUAL_MATURITY_AGE=1defmodel_population_growth(generations:int,lifespan:int,sexual_maturity_age:int=SEXUAL_MATURITY_AGE)->int:"""
Models population growth dynamics over time.
Params:
generations (int): The number of time points a population will go through
before a census on their size.
lifespan (int): The lifespan of any given member of the population.
sexual_maturity_age (int, optional): The age at maturity for any given member of
the population. Defaults to the value of SEXUAL_MATURITY_AGE.
Returns:
int: The number of members in a population after a given number of generations.
Examples:
>>> population_size = model_population_growth(5, 10)
>>> print(population_size)
10
"""# A list of length equal to the lifespan of a population member# Each element in the list is a bin for members at that stage in lifepopulation=[1]+(lifespan-1)*[0]# Iterating `generations` minus 1 times to get the population size after `generations` timesfor_inrange(generations-1):# Subset for the sexually mature populationsexually_mature_members=population[sexual_maturity_age:]# Each member produces 1 offspringoffspring=sum(sexually_mature_members)# Adding offspring to the earliest stage of lifepopulation=[offspring]+population[:-1]returnsum(population)
classAnimal(object):def__init__(self):"""Initialize an Animal object with an initial age of 0."""self.age=0@propertydefreached_lifespan(self):"""
Check if the animal has reached its lifespan.
Returns:
bool: True if the animal has reached its lifespan, False otherwise.
"""returnself.age>=LIFESPAN@propertydefis_sexually_mature(self):"""
Check if the animal is sexually mature.
Returns:
bool: True if the animal is sexually mature, False otherwise.
"""returnself.age>SEXUAL_MATURITY_AGEdefprocreate(self):"""
Procreate and return a new Animal instance if the animal is sexually mature.
Returns:
Animal|None: A new Animal instance if the animal is sexually mature, None otherwise.
"""ifself.is_sexually_mature:returnself.__class__()defepoch(self):"""Increment the animal's age by 1."""self.age+=1classPopulation(object):def__init__(self,nanimals:int):"""
Initialize a Population object with a specified number of animals.
Args:
nanimals (int): The number of animals in the population.
"""self.animals=[Animal()for_inrange(nanimals)]defprocreate(self):"""Procreate and add offspring to the population for sexually mature animals."""fori,_inenumerate(self.animals):offspring=self.animals[i].procreate()ifoffspringisnotNone:self.animals.append(offspring)defcull(self):"""Remove animals from the population that have reached their lifespan."""self.animals=[animalforanimalinself.animalsifnotanimal.reached_lifespan]defepoch(self):"""Advance the population by one epoch, incrementing the age of each animal."""foranimalinself.animals:animal.epoch()defcensus(self):"""
Count the number of animals in the population.
Returns:
int: The number of animals in the population.
"""returnlen(self.animals)