【问题标题】:Indices of matching parentheses in PythonPython中匹配括号的索引
【发布时间】:2015-07-11 13:59:45
【问题描述】:

有没有办法获取字符串中匹配括号的索引?例如这个:

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

我想要一本带值的字典:

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

这意味着索引 4 和 14 上的括号匹配 , 7 和 8 等等。 非常感谢。

【问题讨论】:

  • 很明显有only one obvious way可以用Python写简单的算法,因为你在5分钟内得到了三倍几乎相同的答案。

标签: python parentheses


【解决方案1】:

您的意思是自动化方式? 我不这么认为。

您需要使用堆栈创建一个程序,在其中找到左括号时将索引压入,找到右括号时将其弹出。

在 Python 中,您可以轻松地将 list 用作 stack,因为它们具有 append()pop() 方法。

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

希望这会有所帮助。

【讨论】:

  • 我同意堆栈是要走的路。这只会捕获不平衡的 open 括号,但是:太多的 close 括号会导致从空列表中弹出。
  • 感谢提示,现在答案更完整了。
【解决方案2】:

检查平衡括号的标准方法是使用堆栈。在 Python 中,这可以通过附加到标准列表并从标准列表中弹出来完成:

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)

结果:

In [58]: d
Out[58]: {4: 14, 7: 8, 9: 10}

【讨论】:

    【解决方案3】:

    也试试这个。

    def match(str):
        stack = []
        ans = {}
        for i,ch in enumerate(str):
            if ch == "(":
                stack.append(i)
            else :
                try:
                    if ch == ")":
                        ans[stack.pop()] = i
                        continue
                except:
                    return False
                
        if len(stack) > 0:
            return False
        else:
            return ans
    
    test_str = "()"
    print(match(test_str))
    
    

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 2020-06-05
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多