Python program to check matching of simple parentheses

后端 未结 25 2408
谎友^
谎友^ 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:38

    In case u also need to find the position of the first mismatching bracket from left u can use the below code which also cover certain edge cases:

    def isBalanced(expr):
        opening=set('([{')
        new=set(')]}{[(')
        match=set([ ('(',')'), ('[',']'), ('{','}') ])
        stack=[]
        stackcount=[]
        for i,char in enumerate(expr,1):
            if char not in new:
                continue
            elif char in opening:
                stack.append(char)
                stackcount.append(i)
            else:
                if len(stack)==0:
                    print(i)
                    return False
                lastOpen=stack.pop()
                lastindex=stackcount.pop()
                if (lastOpen, char) not in match:
                    print (i)
                    return False
        length=len(stack)
        if length!=0:
          elem=stackcount[0]
          print (elem)
        return length==0
    string =input()
    ans=isBalanced(string)
    if ans==True:
        print("Success")
    

提交回复
热议问题