列表中所有对的最低公倍数

时间:2010-09-10 01:17:26

标签: python algorithm

我有一些代码可以计算数字列表的最低公倍数。我想修改此代码以返回一个值列表,这些值表示我的号码列表中每对的最低公倍数。

def lcm(numbers):
    return reduce(__lcm, numbers)

def __lcm(a, b):
    return ( a * b ) / __gcd(a, b)

def __gcd(a, b):
    a = int(a)
    b = int(b)
    while b:
        a,b = b,a%b
    return a

如果输入为[3, 5, 10],则输出为[lcm(5,10)=10, lcm(3,5)=15, lcm(3,10)=30](不需要排序)。

我觉得有一些优雅的方法来计算这个最低公倍数的列表,但是如果没有一些例子我就无法掌握它。

2 个答案:

答案 0 :(得分:4)

你看起来很棒。我只会改变你的答案:

def lcm(numbers):
    return map(__lcm, combinations( numbers, 2 ) )

我正在使用来自itertools的combinations

答案 1 :(得分:3)

鉴于你现有的函数(编辑了__gcd()来返回a而不是no):

from itertools import combinations

inlist = [3, 5, 10]

print [lcm(pair) for pair in combinations(inlist, 2)]
相关问题