Python program to check matching of simple parentheses

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

    just modified Henry Prickett-Morgan's code a little bit to handle it more sensibly, namely taking into account that the number of "(" matches that of ")" but string starts with ")" or ends with "(" which are apparently not right.

    
    def ValidParenthesis(s):
        count = 0
        if s[0] == ')' or s[-1] == '(':
          return False
        else:
          for c in s:
            if c == '(':
              count += 1
            elif c == ')':
              count -= 1
            else:
              continue
          return count == 0
    
    

提交回复
热议问题