Favorite non-python language trick?

Peter Otten __peter__ at web.de
Sun Jul 3 04:42:08 EDT 2005


Steven D'Aprano wrote:

> How do you replace:
> 
> reduce(lambda x,y: x*y-1/y, sequence)
> 
> with sum?
 
missing = object()

def my_reduce(f, items, first=missing):
    class adder:
        def __init__(self, value):
            self.value = value
        def __add__(self, other):
            return adder(f(self.value, other))

    if first is missing:
        items = iter(items)
        try:
            first = items.next()
        except StopIteration:
            raise TypeError
    return sum(items, adder(first)).value

if __name__ == "__main__":
    sequence = map(float, range(10))
    r = reduce(lambda x, y: x*y-1/y, sequence)
    s = my_reduce(lambda x, y: x*y-1/y, sequence)
    assert r == s

:-)

Peter




More information about the Python-list mailing list