map, filter & reduce...

Peter Otten __peter__ at web.de
Sun Nov 16 08:11:39 EST 2003


Ben wrote:

> Hi all,
> 
> I'm trying to figure out how how complex map, filter and reduce work
> based on the following piece of code from
> http://www-106.ibm.com/developerworks/linux/library/l-prog.html :
> 
> bigmuls = lambda xs,ys: filter(lambda (x,y):x*y > 25, combine(xs,ys))
> combine = lambda xs,ys: map(None, xs*len(ys), dupelms(ys,len(xs)))
> dupelms = lambda lst,n: reduce(lambda s,t:s+t, map(lambda l,n=n:
> [l]*n, lst))
> print bigmuls((1,2,3,4),(10,15,3,22))
> 
> The solution generated by the above code is: [(3, 10), (4, 10), (2,
> 15), (3, 15), (4, 15), (2, 22), (3, 22), (4, 22)]
> 
> I'm stuck on the second line in "map(None, xs*len(ys),
> dupelms(ys,len(xs))"... Can someone explain me how the map function
> evaluates??
> 
> Thanks
> Ben

Do yourself a favour and read on to the sane version that uses a list
comprehension :-) By the way, David Mertz has deliberately obfuscated the
traditional imperative approach by not preserving the block structure and
inserting superfluous comments.

map(None, seq1, seq2) returns a list of tuples (seq1[0], seq2[0]) etc. The
sequence item is substituted with None, if a sequence is exhausted, e. g.

>>> map(None, range(3), range(2))
[(0, 0), (1, 1), (2, None)]
>>>

but that doesn't occur here, making zip() instead of map() a better choice.

Putting it all together:
dupelms() takes a list and a length n creating a new list where each item of
the original list is duplicated n times:

>>> dupelms(range(3), 2)
[0, 0, 1, 1, 2, 2]
>>>

This is then zipped (though by map())
with a list similar to 
>>> range(2)*3
[0, 1, 0, 1, 0, 1]

>>> map(None, [0,0,1,1,2,2], [0,1,0,1,0,1])
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
>>>

This last list is then filtered for items (the tuples), that meet the
condition
item[0]*item[1] > 25

To imagine how errorprone this code is and to check how well it scales with
large lists is left as an exercise to the reader...

Peter




More information about the Python-list mailing list