Rosalind第11題:Mortal Fibonacci Rabbits
Problem
Figure 4.A figure illustrating the propagation of Fibonacci's rabbits if they die after three months.
Recall the definition of theFibonacci numbersfrom“Rabbits and Recurrence Relations”, which followed therecurrence relationand assumed that each pair of rabbits reaches maturity in one month and produces a single pair of offspring (one male, one female) each subsequent month.
Our aim is to somehow modify this recurrence relation to achieve adynamic programmingsolution in the case that all rabbits die out after a fixed number of months. SeeFigure 4for a depiction of a rabbit tree in which rabbits live for three months (meaning that they reproduce only twice before dying).
Given:Positive integersand.
Return:The total number of pairs of rabbits that will remain after the-th month if all rabbits live formonths.
Sample Dataset
6 3
Sample Output
4
python解決方案
# coding=utf-8 ### 11. Mortal Fibonacci Rabbits ### # 0 1 1 2 2 3 4 5 7 9 12 # method1 def fibonacciRabbits(n, m): F = [0, 1, 1] for i in range(3, n + 1): if i <= m: total = F[i - 1] + F[i - 2] elif i == m + 1: total = F[i - 1] + F[i - 2] - 1 else: total = F[i - 1] + F[i - 2] - F[i - m - 1] F.append(total) print(F) return (F[n]) print (fibonacciRabbits(6,3))