因此,我已经看到了一些解决该问题或类似问题的方法,但是我真的很想知道为什么我的方法不起作用。它比我发现的许多解决方案都容易阅读,因此,我很想使其实用!

从1对兔子开始,将在2个月后开始繁殖。运行n个月,兔子存活m个月后死亡。
输入“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))

谢谢=]

最佳答案

这是从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))

10-07 18:51