16 May 2023 · filed under Coding challenge

Rosalind: Rabbits and Recurrence Relations

pythonrosalindbioinformaticspopulation-modelsrecursion

Solution #1

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)