[Python] reduce examples?

Bob Miller kbob at jogger-egg.com
Fri Dec 1 20:56:00 PST 2006


Rob Hudson wrote:

> Now that we're using Python more at work I thought I'd skim the Python 
> tutorial for things I might have read at one time but have forgotten.
> 
> I understand the description of "reduce" but I'm having a hard time 
> thinking of real world examples of when/why you'd use it.  Can anyone 
> throw out some examples:
> http://www.python.org/doc/current/tut/node7.html#SECTION007130000000000000000

from operator import mul, sub

def is_leap_year(year):
    return bool(reduce(sub, [year % y == 0 for y in (4, 100, 400)]))
    # (Insert tongue T into cheek C.)

def dot_product(v0, v1):
    return reduce(lambda a, b: a + b[0] * b[1], zip(v0, v1), 0)

def factorial(n):
    return reduce(mul, range(1, n+1))

def inet_aton(a):
    # man 3 inet_aton
    def shift_or(w, q):
	return w << 8 | q;
    return reduce(shift_or, [int(q) for q in a.split('.'), 0L)

Python has been gradually deprecating reduce.  The builtins sum, min
and max are now able to reduce a sequence of values, and those
were the three most common uses for reduce.

-- 
Bob Miller                              K<bob>
                                        kbob at jogger-egg.com


More information about the Python mailing list