views:

73

answers:

2

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.

+3  A: 

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.

wheaties
+2  A: 

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)]
kindall
Also, if you want to eliminate duplicates in the input list: print [lcm(pair) for pair in combinations(set(inlist), 2)]
kindall
good catch on returning 'a' that was a typo in my copy paste
spoon16