Python program to check matching of simple parentheses

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

        #function to check if number of closing brackets is equal to the number of opening brackets
        #this function also checks if the closing bracket appears after the opening bracket
        def matched(str1):
            if str1.count(")")== str1.count("("):
                p1=str1.find("(")
                p2=str1.find(")")
                if p2 >= p1:
                    str1=str1[p1+1:p2]+ str1[p2+1:]
                    if str1.count(")")>0 and str1.count("(")>0:
                        matched(str1)
                    return True
                else:
                    return False
            else:
                return False
    
        matched(str1)
    

提交回复
热议问题