列表中所有对的最小公倍数
我有一段代码,它可以计算一组数字的最小公倍数。我想修改这段代码,让它返回一个值的列表,表示我数字列表中每一对数字的最小公倍数。
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 个回答
3
根据你现有的函数(把 __gcd() 修改为返回 a,而不是不返回任何东西):
from itertools import combinations
inlist = [3, 5, 10]
print [lcm(pair) for pair in combinations(inlist, 2)]
4
你现在的代码看起来不错。我只会建议你改一下生成答案的方式:
def lcm(numbers):
return map(__lcm, combinations( numbers, 2 ) )
在这里,我使用了来自 itertools 的 combinations
函数。