Useful code which uses reduce()? [closed] Useful code which uses reduce()? [closed] python python

Useful code which uses reduce()? [closed]


The other uses I've found for it besides + and * were with and and or, but now we have any and all to replace those cases.

foldl and foldr do come up in Scheme a lot...

Here's some cute usages:

Flatten a list

Goal: turn [[1, 2, 3], [4, 5], [6, 7, 8]] into [1, 2, 3, 4, 5, 6, 7, 8].

reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])

List of digits to a number

Goal: turn [1, 2, 3, 4, 5, 6, 7, 8] into 12345678.

Ugly, slow way:

int("".join(map(str, [1,2,3,4,5,6,7,8])))

Pretty reduce way:

reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)


reduce() can be used to find Least common multiple for 3 or more numbers:

#!/usr/bin/env pythonfrom fractions import gcdfrom functools import reducedef lcm(*args):    return reduce(lambda a,b: a * b // gcd(a, b), args)

Example:

>>> lcm(100, 23, 98)112700>>> lcm(*range(1, 20))232792560


reduce() could be used to resolve dotted names (where eval() is too unsafe to use):

>>> import __main__>>> reduce(getattr, "os.path.abspath".split('.'), __main__)<function abspath at 0x009AB530>