Check if given Parentheses expression is balanced or not | Function to check if parenthesis are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more closing parenthesis than opening ; If count is not zero , it means there are more opening parenthesis ; Driver code
def isBalanced ( exp ) : NEW_LINE INDENT flag = True NEW_LINE count = 0 NEW_LINE for i in range ( len ( exp ) ) : NEW_LINE INDENT if ( exp [ i ] == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT exp1 = " ( ( ( ) ) ) ( ) ( ) " NEW_LINE if ( isBalanced ( exp1 ) ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Balanced " ) NEW_LINE DEDENT exp2 = " ( ) ) ( ( ( ) ) " NEW_LINE if ( isBalanced ( exp2 ) ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Balanced " ) NEW_LINE DEDENT DEDENT