Finally, a use for reduce

I’ve been using Python for a long time but I’m not sure that I’ve ever used the reduce.  A lot of people use it badly and I’ve never really “gotten” it.  But the other day I was tackling a problem and a light bulb went off in my head — “Isn’t this what reduceis for?”

The problem is that I had a list of regular expressions that I wanted to apply to a string and, if once of those hit, I wanted to return True.  Of course, I could put all those strings in one regular expression but I wanted to be able to add and take out those regular expressions on an ad hoc way.  And I don’t want to make three or four simple regex’s into one complex one.

So here is an example of what I did, in a contrived sort of way:


import re

flintstones=["Fred","Wilma","Pebbles"]

def inFamily(p):
resultlist = [re.search(x,p) for x in flintstones]

return reduce(lambda x,y: x or y, result
list)


print inFamily(”Fred”)
print inFamily(”Barney”)

So the first called to inFamily returns a MatchObject (or, really, True) and the second returns None (or, really, False).

In the right context, reduce turns a complex problem into a simple one.

Powered by ScribeFire.

Leave a Reply

You must be logged in to post a comment.