find the greatest common divisor of a list of numbers in python

One way to find the greatest common divisor (GCD) of a list of numbers is to use the built-in math.gcd() function and the reduce() function from the functools module.

main.py
import math
from functools import reduce

def gcd_list(numbers):
    return reduce(math.gcd, numbers)
102 chars
6 lines

Alternatively, you can implement the GCD computation using recursion:

main.py
def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

def gcd_list(numbers):
    result = numbers[0]
    for i in range(1, len(numbers)):
        result = gcd(result, numbers[i])
    return result
216 chars
11 lines

Finally, you can use a list comprehension to find the GCD of the list:

main.py
def gcd_list(numbers):
    return reduce(lambda x, y: math.gcd(x, y), numbers)
79 chars
3 lines

gistlibby LogSnag