Fibonacci兔子在任意数月之后死亡

spa*_*det 11 python fibonacci rosalind

所以,我已经看到了针对这个问题或类似问题的一些解决方案,但我真的想知道为什么 我的工作不起作用.它比我找到的很多解决方案更容易阅读,所以我很乐意让它发挥作用!

从1对兔子开始,2个月后开始繁殖.跑了n个月,兔子在生活了几个月后就死了.输入'6 3'应该返回4,但它返回3.

#run for n months, rabbits die after m months.
n, m = input("Enter months to run, and how many months rabbits live, separated by a space ").split() 
n, m = int(n), int(m)
generations = [1, 1, 2] #Seed the sequence with the 1 pair, then in their reproductive month.
def fib(i, j):
    count = 3 #we start at the 3rd generation.
    while (count < i):
        if (count < j):
            generations.append(generations[count-2] + generations[count-1]) #recurrence relation before rabbits start dying
        else:                                                               #is just the fib seq (Fn = Fn-2 + Fn-1)
            generations.append((generations[count-2] + generations[count-1]) - generations[(count-j)])  #Our recurrence relation when rabbits die every month
        count += 1                                                          #is (Fn = Fn-2 + Fn-1 - Fn-j)
    return (generations[count-1])


print (fib(n, m))
print ("Here's how the total population looks by generation: \n" + str(generations))
Run Code Online (Sandbox Code Playgroud)

谢谢=]

小智 2

这是从 SpaceCadets 问题的答案中复制的,以帮助将其从“未回答”的问题列表中删除。


这里的两个关键是将树绘制到一个很大的数字,并确保包括对第一代和第二代死亡的基本情况检查(在两种情况下都是 -1,然后它取决于输入)。

所以有3个潜在的案例。当我们不需要考虑死亡时的常规 fib 序列,第一代和第二代死亡用递归关系 Fn-2 + Fn-1 - Fn-(monthsAlive+1) 初始化我们的最终序列

我确信有一种方法可以合并其中的 1 或 2 个检查并使算法更加高效,但到目前为止,它立即正确地解决了大型测试用例 (90, 17)。所以我很高兴。

经验教训:使用整个白板。

#run for n months, rabbits die after m months.
n, m = input("Enter months to run, and how many months rabbits live, separated by a space ").split() 
n, m = int(n), int(m)
generations = [1, 1] #Seed the sequence with the 1 pair, then in their reproductive month.
def fib(i, j):
    count = 2
    while (count < i):
        if (count < j):
            generations.append(generations[-2] + generations[-1]) #recurrence relation before rabbits start dying (simply fib seq Fn = Fn-2 + Fn-1)
        elif (count == j or count == j+1):
            print ("in base cases for newborns (1st+2nd gen. deaths)") #Base cases for subtracting rabbit deaths (1 death in first 2 death gens)
            generations.append((generations[-2] + generations[-1]) - 1)#Fn = Fn-2 + Fn-1 - 1
        else:
            generations.append((generations[-2] + generations[-1]) - (generations[-(j+1)])) #Our recurrence relation here is Fn-2 + Fn-1 - Fn-(j+1)
        count += 1
    return (generations[-1])


print (fib(n, m))
print ("Here's how the total population looks by generation: \n" + str(generations))
Run Code Online (Sandbox Code Playgroud)