Indices of matching parentheses in Python

杀马特。学长 韩版系。学妹 提交于 2019-11-29 04:25:38

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.

Bas Swinckels

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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!