Parentheses pairing ({}[]()<>) issue

前端 未结 9 1539
醉酒成梦
醉酒成梦 2021-02-06 00:27

I want to be able to pair up all parentheses in a string, if they aren\'t paired then then they get their index number and False. It seems like it is repeating some values over

9条回答
  •  时光说笑
    2021-02-06 00:53

    iparens = iter('(){}[]<>')
    parens = dict(zip(iparens, iparens))
    closing = parens.values()
    
    def balanced(astr):
        stack = []
        for c in astr:
            d = parens.get(c, None)
            if d:
                stack.append(d)
            elif c in closing:
                if not stack or c != stack.pop():
                    return False
        return not stack
    

    Example:

    >>> balanced('[1<2>(3)]')
    True
    >>> balanced('[1<2(>3)]')
    False
    

提交回复
热议问题