Rosalind: Rabbits and Recurrence Relations

Python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from functools import lru_cache

@lru_cache
def model_population_growth(n: int, k: int, pop: int = 1) -> int:
    """
    Calculates the rabbit population after `n` months using the Fibonacci sequence.

    Args:
        n (int): The number of months.
        k (int): The number of offspring per rabbit pair.
        pop (int, optional): The initial population. Defaults to 1.

    Returns:
        int: The rabbit population after `n` months.

    Examples:
        >>> rabbit_population = rabbitPop(5, 3)
        >>> print(rabbit_population)
        19
    """
    if n == 1 or n == 2:
        return pop
    return rabbitPop(n - 1, k) + (rabbitPop(n - 2, k) * k)
0%