finding indices in a sequence of parentheses

tiissa tiissa at nonfree.fr
Sun May 29 17:46:27 EDT 2005


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).



More information about the Python-list mailing list