I am new to Python language, and I am running into this problem, the code below is not returning the expecting value:
def rabbits(n):
first = 1
second = 1
if n == 1 or n == 2:
return 1
while n > 2:
first, second = second, first + second
n -= 1
if n > 5:
die1 = 1
die2 = 1
if n == 6 or n == 7:
return second - 1
while n > 7:
die1, die2 = die2, die1 + die2
n -= 1
return second - die2
return second
I am hoping that rabbits(6) would be returning 7, but it returns 8 instead. Can anyone help me find the wrong stuff in here? Thanks!
You first reduce
nto 2 or lower (while n > 2: .. n -= 1), then test ifn > 5.That latter test is never going to pass because
nwill now always be 2 or lower.That first reduction calculates the fibonacci sequence, and the 6th value in that sequence is 8 (after 1, 1, 2, 3 & 5).
To avoid your problem, use a simple range loop instead:
Now
iwill go from 6 to 3 without changingn.