Check for balanced parentheses in Python

PythonServer Side ProgrammingProgramming

Many times we are required to find if an expression is balanced with respect to the brackets present in it. By balanced we mean for each left bracket there is a corresponding right bracket and the sequence of brackets is properly ordered. This has importance in writing a program or a mathematical expression where brackets are heavily used. In this topic, we will see how we can programmatically find out if an expression containing brackets is balanced or not.

Through Elimination

In this method, we find out the innermost pair of brackets and replace them with null values. We keep doing this till all the pairs of brackets are replaced. If still some bracket is left then the expression is not balanced otherwise the expression is found to be balanced.


def brackets(expression):
   all_br = ['()', '{}', '[]']
   while any(x in expression for x in all_br):
      for br in all_br:
         expression = expression.replace(br, '')
   return not expression

# calling the function
input_string = "([]{}()"
if brackets(input_string):
   print(input_string,"Not balanced")


Running the above code gives us the following result −

([]{}() Not balanced
Updated on 17-Oct-2019 11:53:22