开发者

Lowest common multiple for all pairs in a list

开发者 https://www.devze.com 2023-01-15 07:27 出处:网络
I have some code that calculates the lowest common multiple for a list of numbers.I would like to modify this code to return a list of values that represents the lowest common multiple for each pair i

I have some code that calculates the lowest common multiple for a list of numbers. I would like to modify this code to return a list of values that represents the lowest common multiple for each pair in my number list.

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

If the input is [3, 5, 10] the output would be [lcm(5,10)=10, lcm(3,5)=15, lcm(3,10)=30] (sorting not required).

I feel like there is some elegant way of calculating this list of lowest common multiples but I'm not able to grasp it without some example.


What you have looks good. I'd only change how you produce the answer:

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

where I'm using combinations from itertools.


Given your existing functions (with __gcd() edited to return a, rather than none):

from itertools import combinations

inlist = [3, 5, 10]

print [lcm(pair) for pair in combinations(inlist, 2)]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号