Update some snippets

This commit is contained in:
Angelos Chalaris
2019-08-20 11:08:01 +03:00
parent 34df36a961
commit 3a3c618619
3 changed files with 32 additions and 36 deletions

View File

@ -1,41 +1,36 @@
---
title: lcm
tags: math
tags: math,list,recursion,advanced
---
Returns the least common multiple of two or more numbers.
Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. The GCD formula uses recursion.
Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.
Use `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple.
```py
from functools import reduce
import math
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def lcm(*args):
numbers = []
numbers.extend(spread(list(args)))
numbers = []
numbers.extend(spread(list(args)))
def _gcd(x, y):
return x if not y else _gcd(y, x % y)
def _lcm(x, y):
return int(x * y / math.gcd(x, y))
def _lcm(x, y):
return x * y / _gcd(x, y)
return reduce((lambda x, y: _lcm(x, y)), numbers)
return reduce((lambda x, y: _lcm(x, y)), numbers)
```
```py
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60