Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indices of matching parentheses in Python

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.

like image 915
Peter Gubik Avatar asked May 01 '15 17:05

Peter Gubik


People also ask

How do you compare parentheses in Python?

In this approach, you can make use of recursion, i.e., conditional statements and loop to match the parentheses, and if it returns true, the parentheses are valid; otherwise, not. Here we make use of the while loop to check the sequence of parentheses and return the output whether the parentheses are valid or not.

How do I find matching brackets in Python?

One approach to check balanced parentheses is to use stack. Each time, when an open parentheses is encountered push it in the stack, and when closed parenthesis is encountered, match it with the top of stack and pop it. If stack is empty at the end, return Balanced otherwise, Unbalanced.

What is parenthesis matching problem?

The valid parentheses problem involves checking that: all the parentheses are matched, i.e., every opening parenthesis has a corresponding closing parenthesis. the matched parentheses are in the correct order​, i.e., an opening parenthesis should come before the closing parenthesis.


2 Answers

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.

like image 86
Baltasarq Avatar answered Oct 08 '22 09:10

Baltasarq


The standard way to check for balanced brackets is to use a stack. In Python, this can be done by appending to and popping from a standard list:

text = 'aaaa(bb()()ccc)dd'
istart = []  # stack of indices of opening parentheses
d = {}

for i, c in enumerate(text):
    if c == '(':
         istart.append(i)
    if c == ')':
        try:
            d[istart.pop()] = i
        except IndexError:
            print('Too many closing parentheses')
if istart:  # check if stack is empty afterwards
    print('Too many opening parentheses')
print(d)

Result:

In [58]: d
Out[58]: {4: 14, 7: 8, 9: 10}
like image 34
Bas Swinckels Avatar answered Oct 08 '22 10:10

Bas Swinckels