Sachin
Sachin

Reputation: 73

TypeError in python - missing 1 required positional argument

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 run wabbits(5), I get 19, but when I run wabbits(5, 3) after the function below, I get

TypeError: wabbits() missing 1 required positional argument: 'k'

What am I doing wrong?

def wabbits(n, k):
    if n == 1:
        return 1
    if n == 2:
        return 1
    return wabbits(n-2)*k + wabbits(n-1)

Upvotes: 0

Views: 8808

Answers (3)

cdarke
cdarke

Reputation: 44344

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)

Upvotes: 0

mhawke
mhawke

Reputation: 87064

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.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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

Upvotes: 4

Related Questions