rabbit.jpg

This problem asks:

Given: Positive integers n≤100 and m≤20.

Return: The total number of pairs of rabbits that will remain after the n-th month if all rabbits live for m months.

Restate the problem

This is a rabbit population model similar to fibd. The difference here is that every pair of rabbits has a generation of two offspring every month until they die after m months.

Solution steps

My first challenge was to keep track of the rabbit population history so that I could go back and account for the correct number of rabbits dying of old age.

To do that, created a Python list where each element in the list is the population of rabbit pairs for a given generation. I knew the population of rabbit pairs for the first two generations, so I filled them in as the first values. Python’s counting from zero often confuses me when I try to refer to items in a list by their index, so I added a zero generation at the beginning.

    history = [0, 1, 1]

Then, I got stuck trying to calculate all the list indices from the beginning. After considerable struggle, I realized that it’s much easier to calculate them based on how far they are from end of the list, so I read this to learn about negative list indexing in Python.

Next, I realized that there’s nothing special about the rabbit population before rabbits start dying, so in that case it’s just:

if i < m:
    history.append(history[-1] + history[-2])

In the generation when rabbits start dying of old age, only that first, oldest pair of rabbits dies, so:

if i == m:
    history.append(history[-1] + history[-2] - 1)

… and the complicated case is when i < m, so I need to figure out how many pairs of rabbits to kill off.

if i > m:
    history.append((history[-1] + history[-2]) - history[-m-1])

These three statements worked to give me correct answer.

Python concepts

Learning about the negative indexing mechanism was the key to me solving this problem, although I still think it’s possible to calculate the indexes from the start of the list, the code I have works.

Bioinformatics concepts

One common theme in bioinformatics is building computational models for living systems like reproducing rabbits and the likelihood of genetic outcomes over generations. There is a fascinating paper on the topic here.