I\'m stuck here. For n = 5
and k = 3
, the answer should be 19
. If I set k = 3
separately as a local or global variable and ru
Calling the function with wabbits(5)
will not work because the function is declared to accept 2 parameters: n
and k
. Both must be supplied.
You can call the function with two arguments, but the trouble is that the recursive call to wabbits()
passes only a single argument:
wabbits(n-2) * k + wabbits(n-1)
This is two calls to wabbits()
the first has one argument n-2
and the second also has only one argument n-1
. Since wabbits()
must be called with two arguments a TypeError` exception is raised as you observed.
Your wabbits()
function takes two arguments:
def wabbits(n, k):
# 1 2
but your code calls it with just one:
return wabbits(n-2)*k + wabbits(n-1)
# ^^^ ^^^^
You need to pass in a value for k
as well. You could just pass in the current value of k
:
def wabbits(n, k):
if n == 1:
return 1
if n == 2:
return 1
return wabbits(n-2, k)*k + wabbits(n-1, k)
# 1 2 1 2
and indeed that produces 19:
>>> def wabbits(n, k):
... if n == 1:
... return 1
... if n == 2:
... return 1
... return wabbits(n-2, k)*k + wabbits(n-1, k)
...
>>> wabbits(5, 3)
19
Several solutions, the simplest is:
def wabbits(n, k):
if n == 1:
return 1
elif n == 2:
return 1
return wabbits(n-2, k)*k + wabbits(n-1, k)
r = wabbits(5, 3)
However you could encapsulate k
using an inner function:
def wabbits(n, k):
def bunnies(rn):
if rn == 1:
return 1
elif rn == 2:
return 1
return bunnies(rn-2)*k + bunnies(rn-1)
return bunnies(n)
r = wabbits(5, 3)