Reputation: 48392
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.
Upvotes: 1
Views: 2740
Reputation: 35970
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.
Upvotes: 4
Reputation: 184101
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)]
Upvotes: 3