Python program to check matching of simple parentheses

后端 未结 25 2336
谎友^
谎友^ 2020-12-01 17:02

I am a Python newbie and I came across this exercise of checking whether or not the simple brackets \"(\", \")\" in a given string are matched evenly.

I have seen ex

相关标签:
25条回答
  • 2020-12-01 17:40

    My solution here works for brackets, parentheses & braces

    openList = ["[","{","("]
    closeList = ["]","}",")"]
    def balance(myStr):
        stack= []
        for i in myStr:
            if i in openList:
                stack.append(i)
            elif i in closeList:
                pos = closeList.index(i)
                if ((len(stack) > 0) and (openList[pos] == stack[len(stack)-1])):
                    stack.pop()
                else:
                    return "Unbalanced"
        if len(stack) == 0:
            return "Balanced"
    print balance("{[()](){}}") 
    
    0 讨论(0)
提交回复
热议问题