1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| from operator import add, mul, truediv def reduce(f, s, initial): """Combine elements of s pairwise using f, starting with initial.
>>> reduce(mul, [2, 4, 8], 1) 64 """ if not s: return initial else: first, rest = s[0], s[1:] return reduce(f, rest, f(initial, first))
def reduce2(f, s, initial): """Combine elements of s pairwise using f, starting with initial.
>>> reduce2(mul, [2, 4, 8], 1) 64 >>> reduce2(pow, [1, 2, 3, 4], 2) 16777216 """ for x in s: initial = f(initial, x) return initial
def divide_all(n, ds): """Divide n by every d in ds.
>>> divide_all(1024, [2, 4, 8]) 16.0 >>> divide_all(1024, [2, 4, 0, 8]) inf """ try: return reduce(truediv, ds, n) except ZeroDivisionError: return float('inf')
|