Reputation: 720
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 ?
Upvotes: 1
Views: 659
Reputation: 7734
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)
.
Upvotes: 1
Reputation: 599630
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))
Upvotes: 2
Reputation: 8685
Your function is expecting a single variable (a tuple), but you are passing two variables, try this:
return gcd((b, a % b))
Upvotes: 2
Reputation: 19973
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.
Upvotes: 1