Frage

I'm currently learning Python, and I have problems modifying this function to work as I would like. This is a recursive function that finds gcd from two integers. data is a tuple with two integers. How to modify this recursive function to work with one parameter?

def gcd(data):
    a, b = data
    if b == 0: return a
    return gcd(b, a % b)

If i execute it like this, i get

TypeError: checkio() takes 1 positional argument but 2 were given

If I try to gather arguments by defining def gcd(*data):, I get

ValueError: need more than 1 value to unpack.

Is this possible at all ?

War es hilfreich?

Lösung 3

I think you should just be able to put an extra pair of parentheses around your arguments, like so:

return gcd((b, a % b))

This will make your two positional arguments into a tuple passed as a single positional argument.

Alternatively you could drop the unpacking and just accept two positional arguments instead of a single tuple in the first place.

Andere Tipps

Your function is expecting a single variable (a tuple), but you are passing two variables, try this:

return gcd((b, a % b))

Sure, you just need to be consistent. Either define gcd to take two parameters:

def gcd(a, b):

or wrap the values in a tuple when you call it:

return gcd((b, a % b))

Passing a literal tuple as a parameter requires another set of parentheses to make clear that it is not 2 separate parameters:

return gcd((b, a % b))

Alternatively, the tuple could be assigned to a separate name first (with or without parentheses):

next_data = b, a % b
return gcd(next_data)

gcd(*data) would work, but you would also need to change your initial call to pass individual parameters as well, in the form of either gcd(a, b) or gcd(*data).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top