'How do I find the gcd of all numbers in a tuple using math.gcd?

from math import gcd
nums = tuple(map(int,input().split()))
# find gcd of numbers in num

I tried the following code

print(gcd(nums))

but "TypeError: 'tuple' object cannot be interpreted as an integer" occures. How can I solve this problem?



Solution 1:[1]

gcd takes an arbitrary number of positional args not an iterable, you need to unpack your tuple into positional args when you call it.

print(gcd(*nums))

NOTE: This was added in Python 3.9.

Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.

Solution 2:[2]

For Python versions earlier than 3.9, you can use functools.reduce() to build up the result by processing two elements at a time:

from functools import reduce
from math import gcd

reduce(lambda x, y: gcd(x, y), nums, nums[0])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SuperStormer
Solution 2 BrokenBenchmark