parenthesis
Michele Simionato
mis6 at pitt.edu
Wed Nov 6 09:59:39 EST 2002
bokr at oz.net (Bengt Richter) wrote in message
> For speed, I think it might be faster to count position but not use it to get the
> characters, e.g.,
>
> >>> def get_1st(exp):
> ... parens=i=0
> ... for c in exp:
> ... i += 1
> ... if c=='(': parens+=1
> ... elif c==')':
> ... parens -=1
> ... if not parens: return exp[:i]
> ...
> >>> exp = '(a*(b+c*(2-x))+d)+f(s1)'
> >>> get_1st(exp)
> '(a*(b+c*(2-x))+d)'
>
> This is a little different from Lee Harr's post (which BTW looks to me
> like it depends on the first char being '('). I'd expect the above to run a
> little faster.
>
You are right:
parenthesized_group: 130-140 microseconds
Addelim: 620-640 microseconds
Harr: 90-95 microseconds
get_1st: 60-65 microseconds
get_1st wins as the faster approach, more than twice my original
version
using lists (which however was not intended for speed).
> There are dangers in drawing too general conclusions from particular
> examples too ;-)
>
I agree, still it has been instructive to me to compare the various
approaches: I learned something more that just the fact that this is
not a problem for regular expressions (thing that I suspected).
Thanks to everybody,
Michele
More information about the Python-list
mailing list