Try this:
def a(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return a(n-1) + a(n-2) + a(n-3)
The trick is, that you have to cover all the possible values. You weren't covering n == 0
, and the last condition should be an else
, so it's explicit that there can be no other choices.
Notice that the error unsupported operand type(s) for +: 'int' and 'NoneType'
happened before because if none of the conditions was met (for example, when n == 0
) then None
was returned, and at some point in the recursion an int
was added to None
, causing the error. This is why it's important to be very exhaustive when covering all possibilities in a recursion, making sure that all possible cases are being considered.
And by the way: something tells me that you're missing one case. What happens if n == 2? there should be yet another case for handling this.
return 0
at the end of your function. – forivalln == 2
? there should be yet another case for handling this. – Óscar Lópeza, b, c = b, c, a + b + c
will work far better. – georg