Rohit Tanwar 90801ef447 Fixed typoes
2018-01-09 04:40:00 +05:30
2018-01-09 04:11:24 +05:30
2018-01-09 04:40:00 +05:30
2018-01-09 03:19:50 +05:30
2018-01-09 02:08:05 +05:30
2018-01-09 04:21:27 +05:30
2018-01-09 04:37:00 +05:30
2018-01-09 03:26:25 +05:30
2018-01-09 04:17:15 +05:30
2018-01-09 02:00:17 +05:30
2018-01-08 17:47:16 +05:30
2018-01-09 03:19:50 +05:30
2018-01-09 02:59:40 +05:30

Logo

30-seconds-of-code-python

Python implementation of 30-seconds-of-code.

Note:- This is in no way affiliated with the original 30-seconds-of-code

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

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 inbuild module functools. Also defines a method spread for javascript like spreading of arrays.

from functools import reduce


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)

gcd(8,36) # 4

lcm

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.

from functools import reduce


def spread(arg):
    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)))

    def _gcd(x, y):
        return x if not y else gcd(y, x % y)

    def _lcm(x, y):
        return x * y / _gcd(x, y)

    return reduce((lambda x, y: _lcm(x, y)), numbers)

lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60

spread

Implements javascript's spread syntax as a function. Flattens the list(non-deep) and returns an array.

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

Credits

Icons made by Smashicons from www.flaticon.com is licensed by CC 3.0 BY.

Languages
JavaScript 100%