Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: apply an operator over an iterable

sum(iterable) is effectively:

def sum(iterable):
    s = 0
    for x in iterable:
        s = s.__add__(x)
    return s

Does Python have a built-in function that accomplishes this without setting the initial value?

# add is interchangeable with sub, mul, etc.
def chain_add(iterable):
    iterator = iter(iterable)
    s = next(iterator)
    while True:
        try:
            s = s.__add__(next(iterator))
        except StopIteration:
            return s

The problem I have with sum is that it does not work for other types that support the + operator, e.g. Counter.

like image 865
Jordan Avatar asked Dec 15 '22 20:12

Jordan


2 Answers

Try looking into the python reduce() function: You pass in a function, an iterable, and an optional initializer and it would apply the function cumulatively to all the values.

For example:

import functools
def f(x,y):
    return x+y

print functools.reduce(f, [1, 2, 3, 4]) # prints 10
print functools.reduce(f, [1, 2, 3, 4], 10) # prints 20, because it initializes at 10, not 0.

You can change the function based on your iterable, so it's very customizable.

like image 162
Sherwin Wu Avatar answered Dec 22 '22 00:12

Sherwin Wu


In the case of addition:

import operator
reduce(operator.add, iterable)

This will work on iterables that can't be added together using sum. Similarly, you could perform multiplication using

reduce(operator.mul, iterable)
like image 41
David Robinson Avatar answered Dec 21 '22 23:12

David Robinson