gpt4 book ai didi

python - 任意数月后斐波那契兔子死亡

转载 作者:太空狗 更新时间:2023-10-29 18:08:18 24 4
gpt4 key购买 nike

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

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

关于python - 任意数月后斐波那契兔子死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17310051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com