finding indices in a sequence of parentheses

Steven Bethard steven.bethard at gmail.com
Tue May 31 01:20:22 EDT 2005


Raymond Hettinger wrote:
> [Steven Bethard]
> 
>>>I have a list of strings that looks something like:
>>>lst = ['0', '0', '(*)', 'O', '(*', '*', '(*', '*))', '((*', '*)', '*)']
> 
>  . . .
> 
>>>I want the indices:
>>>(2, 2), (4, 7), (6, 7), (8, 9) and (8, 10)
> 
> opener_stack = []
> for i, elem in enumerate(lst):
>     for c in elem:
>         if c == '(':
>             opener_stack.append(i)
>         elif c == ')':
>             print opener_stack.pop(), i
> 

Thanks Raymond, this is definitely an elegant solution. It was also easy 
to add all the error checking I needed into this one.  For the curious, 
my final solution looks something like:

def indices(lst):
     stack = []
     for i, elem in enumerate(lst):
         for c in elem:
             if c == '(':
                 stack.append(i)
             elif c == ')' and not stack:
                 raise Exception('")" at %i without "("' % i)
             elif c == ')':
                 yield stack.pop(), i
             elif c == 'O' and stack:
                 raise Exception('"O" at %i after "(" at %i' %
                                 (i, stack[-1]))
             elif c == '*' and not stack:
                 raise Exception('"*" at %i without "("' % i)
     if stack:
         raise Exception('"(" at %r without ")"' % stack)

Thanks again!

STeVe



More information about the Python-list mailing list