Merge pull request #76 from sandy9999/gcd_edit

modified gcd.md to fewer lines of code
This commit is contained in:
Angelos Chalaris
2019-08-19 14:03:59 +03:00
committed by GitHub
4 changed files with 20 additions and 60 deletions

View File

@ -1,38 +1,17 @@
### gcd
:information_source: `math.gcd` works with only two numbers
Calculates the greatest common divisor of a list of numbers.
Calculates the greatest common divisor between two or more numbers/lists.
The `helperGcdfunction` uses recursion. Base case is when `y` equals `0`. In this case, return `x`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
Uses the reduce function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
Uses the reduce function from the inbuilt module `functools`. Also uses the `math.gcd` function over a list.
```python
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
def gcd(*args):
numbers = []
numbers.extend(spread(list(args)))
def _gcd(x, y):
return x if not y else gcd(y, x % y)
return reduce((lambda x, y: _gcd(x, y)), numbers)
def gcd(numbers):
return reduce(math.gcd, numbers)
```
``` python
gcd(8,36) # 4
gcd([8,36,28]) # 4
```