finding indices in a sequence of parentheses
Peter Otten
__peter__ at web.de
Mon May 30 02:28:55 EDT 2005
tiissa wrote:
> Steven Bethard wrote:
>> (2) Does anyone see an easier/clearer/simpler[1] way of doing this?
>
> I'd personnally extract the parenthesis then zip the lists of indices.
> In short:
>
> >>> def indices(mylist):
> ... lopen=reduce(list.__add__, [[i]*s.count('(') for i,s in
> enumerate(mylist)],[])
> ... lclose=reduce(list.__add__, [[i]*s.count(')') for i,s in
> enumerate(mylist)],[])
> ... return zip(lopen,lclose)
> ...
> >>> indices(lst)
> [(2, 2), (4, 7), (6, 7), (8, 9), (8, 10)]
> >>>
>
> Before returning, you can check if the lists have same size and if the
> '(' has lower or equal index than ')' in each of these couples. If not
> you can raise the appropriate exception.
>
> Disclaimer: not tested further than example above (but confident).
Not tested but confident should be an oxymoron for a programmer. Some
examples:
lst: ['(', '(', ')', ')']
hettinger [(1, 2), (0, 3)]
bethard [(1, 2), (0, 3)]
tiissa [(0, 2), (1, 3)] oops (or am I just spoilt by the XML spec?)
lst: ['(', ')(', ')']
hettinger [(0, 1), (1, 2)]
bethard [(1, 1), (0, 2)] oops
tiissa [(0, 1), (1, 2)]
So far Raymond's solution is my favourite...
Peter
More information about the Python-list
mailing list