zoukankan      html  css  js  c++  java
  • 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 the Fibonacci numbers from “Rabbits and Recurrence Relations”, which followed the recurrence relation Fn=Fn1+Fn2Fn=Fn−1+Fn−2 and 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 a dynamic programming solution in the case that all rabbits die out after a fixed number of months. See Figure 4 for a depiction of a rabbit tree in which rabbits live for three months (meaning that they reproduce only twice before dying).

    Given: Positive integers n100n≤100 and m20m≤20.

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

    Sample Dataset

    6 3
    

    Sample Output

    4

    # 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)
        return (F[n])
    
    # print fibonacciRabbits(6,3)
    
    
    # method2
    def f(n, k):
        s = [0] * (k + 1)  # list *4 [0, 0, 0, 0]   s[0]代表当月出生的兔子,s[k]代表当月死亡的兔子
        s[0] = 1           # [1, 0, 0, 0]
        for x in range(1, n):
            s[1:k + 1] = s[0:k]
            print s
            s[0] = sum(s[2:])
        return sum(s[:-1])
    
    
    print f(10, 3)
    

      

  • 相关阅读:
    SDRAM(3):刷新和仲裁
    SDRAM(2):初始化
    SDRAM(1):基本介绍
    计数器(3):避免多计少计
    协议——SPI
    matlab数字图像处理 入门基础
    gVim编辑器——基本设置、常用命令、代码片段
    Pomelo的Router
    Pomelo聊天室框架
    Pomelo术语解释
  • 原文地址:https://www.cnblogs.com/think-and-do/p/7274013.html
Copyright © 2011-2022 走看看