LCM of a List
The least common multiple (LCM) of some positive whole numbers is the smallest number that all of them divide. Write lcm_of(numbers) that returns the LCM of a list of integers.
- An empty list gives
1. - If any number is
0, the result is0.
Understand the problem
Find the pieces the standard library already has.
What is the LCM of 4 and 6?
The multiples of 4 are 4, 8, 12 ... and of 6 are 6, 12 ... The smallest shared one is 12. Formula: lcm(a, b) = a * b // gcd(a, b), here 24 // 2 = 12.
What does functools.reduce(f, [a, b, c], start) compute?
f(a, f(b, c))f(f(f(start, a), b), c): it folds the list into one value from the left- A list of three results
reduce takes the starting value, applies f to it and the first item, then applies f to that result and the next item, and so on. A fold turns "combine two" into "combine many".
Why is 1 the right result for an empty list?
- It is arbitrary
- 1 is the neutral element of the LCM:
lcm(1, x)isxfor every x - Because Python says so
The result for "no numbers" should be the value that changes nothing when combined: for sums it is 0, for products it is 1, for LCM it is 1. This is why reduce takes a start value.
Write the solution
Use the standard library.
def lcm_of(numbers):
# Write your code here.
pass
Hint 1: a question to ask yourself
If you could combine just two numbers, how would you combine a whole list?
Hint 2: the shape of the answer
functools.reduce(math.lcm, numbers, 1). (math.lcm exists from Python 3.9 and handles zero.) Or build it from math.gcd.
Reflect
Solution
import math
from functools import reduce
def lcm_of(numbers):
return reduce(math.lcm, numbers, 1)
Another way: only gcd
from math import gcd
from functools import reduce
def lcm_of(numbers):
def lcm(a, b):
return 0 if a == 0 or b == 0 else a * b // gcd(a, b)
return reduce(lcm, numbers, 1)
What this tests: functools.reduce, math.gcd and math.lcm, the idea of a neutral start value, and not writing a loop when the library has the tool.
Folding: reduce is the general "combine a list into one value". sum, math.prod, max, all and any are special cases with their own names. Use the named one when it exists.
Why divide before multiplying in your own version? a * b // gcd is fine in Python (integers never overflow), but in other languages a // gcd * b avoids overflow. Good to know for interviews in other languages.
Cost: O(n) gcd calls.
What an interviewer might ask next: Find the smallest number divisible by every number from 1 to 20. (lcm_of(range(1, 21)) is 232792560.)
VISIBLE = 3
CASES = [
(([4, 6],), 12, 'two numbers'),
(([],), 1, 'an empty list'),
(([5],), 5, 'one number'),
(([2, 3, 4, 5],), 60, 'several numbers'),
(([0, 3],), 0, 'a zero'),
(([7, 7, 7],), 7, 'the same number repeated'),
(([6, 10, 15],), 30, 'pairs share factors'),
((list(range(1, 21)),), 232792560, 'one to twenty'),
]