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)
    

      

  • 相关阅读:
    人月神话读后感2
    人月神话读后感1
    自己跟自己聊天的软件2
    做一个自己跟自己聊天的软件
    安装Android开发工具
    阅读笔记6
    阅读笔记5
    第16周学习进度总结
    个人课程总结
    第15周学习进度总结
  • 原文地址:https://www.cnblogs.com/think-and-do/p/7274013.html
Copyright © 2011-2022 走看看