Indices of matching parentheses in Python

Peter Gubik picture Peter Gubik · May 1, 2015 · Viewed 10.5k times · Source

Is there a way to get indices of matching parentheses in a string? For example for this one:

text = 'aaaa(bb()()ccc)dd'

I'd like to get a dictionary with values:

result = {4:14, 7:8, 9:10}

which means that parentheses on index 4 and 14 are matching , 7 and 8 an so on. Thanks a lot.

Answer

Baltasarq picture Baltasarq · May 1, 2015

You mean an automated way? I don't think so.

You need to create a program using a stack, in which you push the index when you find an open parenthesis, and pop it when you find a closing parenthesis.

In Python, you can easily use a list as a stack, since they have the append() and pop() methods.

def find_parens(s):
    toret = {}
    pstack = []

    for i, c in enumerate(s):
        if c == '(':
            pstack.append(i)
        elif c == ')':
            if len(pstack) == 0:
                raise IndexError("No matching closing parens at: " + str(i))
            toret[pstack.pop()] = i

    if len(pstack) > 0:
        raise IndexError("No matching opening parens at: " + str(pstack.pop()))

    return toret

Hope this helps.