Python program to check matching of simple parentheses

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

    Simplest of all , though all of you guys have done good:

    def wellbracketed(s):
        left=[]
        right=[]
        for i in range(0,len(s)):``
            if s[i]=='(':
                left=left+['(']
            elif s[i]==')':
                if len(left)!=0:
                    right=right+[')']
            else:
                return False
    
        return(len(left)==len(right))
    
    0 讨论(0)
  • 2020-12-01 17:13

    A little different one.

    expression = '{(){({)}}'
    brackets = '[](){}'
    stack  = []
    balanced = False
    for e in expression:
        if e in brackets and stack: # Popping from the stack if it is closing bracket
            if stack [-1] == brackets[brackets.index(e)-1]:
                stack.pop()
                balanced = True
                continue # it will go to the new iteration skipping the next if below
        if e in brackets: # Push to stack if new bracket in the expression
            stack .append(e)
            balanced = False
    balanced = 'Balanced' if balanced and not stack  else 'Unbalanced'
    print(balanced, stack)
    
    0 讨论(0)
  • 2020-12-01 17:14

    you can check this code.
    This code don't use stack operations.

    def matched(s):
      count = 0
      for i in s:
        if i is "(":
          count += 1
        elif i is ")":
          if count != 0:
            count -= 1
          else:
            return (False)
    
      if count == 0:
        return (True)
      else:
        return (False)
    
    0 讨论(0)
  • 2020-12-01 17:15

    if the parenthesis sequence is not an issue (strings like )( ) this code is faster :

    def matched_parenthesis(s):
        return s.count('(') == s.count(')')
    

    Tested with 15KB string, it is ~20μs v.s. 1ms iterating over the whole string.

    And for me the order is not an issue as the underlying protocol guaranties that the string is well-formed.

    0 讨论(0)
  • 2020-12-01 17:16

    This checks whether parentheses are properly matched, not just whether there is an equal number of opening and closing parentheses. We use a list as a stack and push onto it when we encounter opening parentheses and pop from it when we encounter closing parentheses.

    The main problem with your solution is that it only counts the number of parentheses but does not match them. One way of keeping track of the current depth of nesting is by pushing opening parentheses onto a stack and popping them from the stack when we encounter a closing parenthesis.

    def do_parentheses_match(input_string):
        s = []
        balanced = True
        index = 0
        while index < len(input_string) and balanced:
            token = input_string[index]
            if token == "(":
                s.append(token)
            elif token == ")":
                if len(s) == 0:
                    balanced = False
                else:
                    s.pop()
    
            index += 1
    
        return balanced and len(s) == 0
    
    0 讨论(0)
  • 2020-12-01 17:16

    Although I'm not proposing a fix to your implementation, I suggest a cleaner and more pythonic version of the @kreld solution:

    def check_parentheses(expr):
        s = []
        for c in expr:
            if c in '(':
                s.append(c)
            elif c in ')':
                if not len(s):
                    break
                else:
                    s.pop()
        else:
            return not len(s)
        return False
    
    # test -----------------------------------------------------------------
    test_expr = [')(', '(()', '())', '(', ')', '((', '))', '(()())', '(())',
                 '()', '()(())']
    for i, t in enumerate(test_expr, 1):
        print '%i\t%s\t%s' % (i, t, check_parentheses(t))
    
    # output ---------------------------------------------------------------
    1       )(      False
    2       (()     False
    3       ())     False
    4       (       False
    5       )       False
    6       ((      False
    7       ))      False
    8       (()())  True
    9       (())    True
    10      ()      True
    11      ()(())  True
    
    0 讨论(0)
提交回复
热议问题