pythonfibonaccirosalind

Fibonacci mortal rabbits with variable fecundity


I'm trying to modify the python code for Fibonacci mortal rabbits in order to vary the fecundity of the rabbits depending on their age. Let's make an example.

My rabbits achieve maturity after 3 months and die after 6 months. During their 4 months of fecundity they produce a different number of offspring depending on their age. When they are 3 months old produce 2 pairs of bunnies, at 4 months produce 3 pairs of bunnies and so on till the sixth month. Each pair of bunnies is formed by a female and a male. In the end I would count the number of pairs not the number of individuals. Fecundity values from the birth to the death:

fecundity = [0, 0, 2, 3, 3, 1]

The python code that I'm using (https://github.com/jschendel/Rosalind/blob/master/011_FIBD.py) is:

n = 12
m = 6
#n = months to run
#m = how many months the rabbits live

# Populate the initial rabbits.
Rabbits = [1]+[0]*(m-1)

# Calculate the new rabbits (bunnies), in a given month.
# Start at use range(1,n) since our initial population is 0 month old.
for month in range(1, n):
    Bunnies = 0
    # Get the number of Rabbits able to old enough to give birth.
    for j in range(1,m):
        Bunnies += Rabbits[(month-j-1)%m]
    # Bunnies replace the old rabbits who died.
    Rabbits[(month)%m] = Bunnies

# Total rabbits is the sum of the living rabbits.
Total_Rabbits = sum(Rabbits)

I'm not sure how to implement the variation of fecundity. Any help is appreciated!

Thank you, Valentina


Solution

  • I came to an answer myself and I really modified the code that I posted previously. I think that now it is much simpler

    import numpy as np
    
    m = 15
    n = 18
    fecundity = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 1, 1, 1])
    Bunnies = np.array([0]*m)
    Rabbits = np.array([1]+[0]*(m-1))
    
    for month in range(0, 18):
        # every month I shift the list of 1 since they're getting older
        Rabbits = np.roll(Rabbits, 1)
        # I set the newborns as 0
        Rabbits[0] = 0
        # I calculate the newborns
        Bunnies = Rabbits * fecundity
        # and then I assign them to the rabbits 0 month old
        Rabbits[0] = sum(Bunnies)
    
    # the sum of Rabbits is the number of final pairs of Rabbits after n months
    Total_Rabbits = sum(Rabbits)
    # 26 Rabbits