所以,我已经看到了一些解决这个问题或类似问题的方法,但我真的很想知道为什么 我的不起作用。它比我找到的许多解决方案更容易阅读,所以我很乐意让它工作!
从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))
谢谢=]