Search code examples
pythonpython-3.xstacklogic

Program to check balanced brackets for equation


I am trying to write a program which checks balanced brackets for equation, my program is checking the brackets but its only looking for brackets and only give the right answer for the bracket but different answer for equation

My expected output is

exp1 = "(2+3)+(1-5)" # True
exp2 = "((3*2))*(7/3))" # False
exp3 = "(3*5))]" # False

My program below:

def is_valid(myStr):
  """ Check the orders of the brackets
      Returns True or False
  """
  opening = ['(', '[', '{']
  closing = [')', ']', '}']
  stack = []
  for i in myStr:
    if i in opening:
        stack.append(i)
    elif i in closing:
        pos = closing.index(i)
        if ((len(stack) > 0) and
            (opening[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            return False
    if len(stack) == 0:
        return True
    else:
        return False
  return 

My program returning me False for all above equations, where am I doing wrong.


Solution

  • Found few bugs and improvements.

    PS: It's better not to use i,j as variable but some meaningful names such as ele, element etc.

    def is_valid(myStr):
        """ Check the orders of the brackets
          Returns True or False
      """
        opening = ['(', '[', '{']
        closing = [')', ']', '}']
        stack = []
        for i in myStr:
            if i in opening:
                stack.append(i)
            elif i in closing:
                pos = closing.index(i)
                if ((len(stack) > 0) and
                        (opening[pos] == stack[-1])):
                    stack.pop()
                else:
                    stack.append(i)
            else:
                pass
        if len(stack) == 0:
            return True
        else:
            return False
    
    
    print(is_valid('(2+3)+(1-5)'))
    print(is_valid('((3*2))*(7/3))'))
    print(is_valid('(3*5))]'))
    # True
    # False
    # False