which re a|l|t|e|r|n|a|t|i|v|e matched?

Skip Montanaro skip at pobox.com
Mon Oct 27 15:46:56 EST 2003


    >> Don't say, "of course".  I would rather stick my hand in a vise than
    >> use reduce() so it wasn't obvious to me. ;-) Thanks for the
    >> suggestion.  I

    Diez> Why won't you use reduce? 

It's not that I "won't".  It's that my algorithmic brain didn't mature in a
functional programming environment, so I rarely, if ever, think to use
reduce, filter, et al.  The meaning of code which uses them never appears
obvious to me.  I always have to read such code very carefully.

    >> suspect Tim's .lastindex solution will be simplest.

    Diez> Sure, tim provided a better solution for getting the index - I
    Diez> didn't check the lib-doc if there is such a function. But my
    Diez> reduce still comes handy when building the actual pattern, doesn't
    Diez> it?

Not for me.  To wit:

    pat = '|'.join(d.keys())

To use Tim's solution I need to parenthesize the individual keys, so there's
an extra transformation on each key:

    pat = '|'.join(['(%s)' for k in d.keys()])

Note that I still have to keep the number of groups < 100:

    keys = d.keys()
    while keys:
        pat = '|'.join(['(%s)' for k in keys[:100]])
        ... search and find index ...
        keys = keys[100:]

(probably with a break for the "found" case and an else: on the while loop
for the "not found" case)

All of those read more naturally to me than solutions using reduce().

Skip





More information about the Python-list mailing list