Check if two expressions with brackets are same | Python3 program to check if two expressions evaluate to same . ; Return local sign of the operand . For example , in the expr a - b - ( c ) , local signs of the operands are + a , - b , + c ; Evaluate expressions into the count vector of the 26 alphabets . If add is True , then add count to the count vector of the alphabets , else remove count from the count vector . ; stack stores the global sign for operands . ; + means True global sign is positive initially ; global sign for the bracket is pushed to the stack ; global sign is popped out which was pushed in for the last bracket ; global sign is positive ( we use different values in two calls of functions so that we finally check if all vector elements are 0. ; global sign is negative here ; Returns True if expr1 and expr2 represent same expressions ; Create a vector for all operands and initialize the vector as 0. ; Put signs of all operands in expr1 ; Subtract signs of operands in expr2 ; If expressions are same , vector must be 0. ; Driver Code
MAX_CHAR = 26 ; NEW_LINE def adjSign ( s , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( s [ i - 1 ] == ' - ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def eval ( s , v , add ) : NEW_LINE INDENT stk = [ ] NEW_LINE stk . append ( True ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' + ' or s [ i ] == ' - ' ) : NEW_LINE i += 1 NEW_LINE continue ; NEW_LINE if ( s [ i ] == ' ( ' ) : NEW_LINE if ( adjSign ( s , i ) ) : NEW_LINE INDENT stk . append ( stk [ - 1 ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT stk . append ( not stk [ - 1 ] ) ; NEW_LINE DEDENT elif ( s [ i ] == ' ) ' ) : NEW_LINE stk . pop ( ) ; NEW_LINE else : NEW_LINE if ( stk [ - 1 ] ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] += ( 1 if add else - 1 ) if adjSign ( s , i ) else ( - 1 if add else 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] += ( - 1 if add else 1 ) if adjSign ( s , i ) else ( 1 if add else - 1 ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT def areSame ( expr1 , expr2 ) : NEW_LINE INDENT v = [ 0 for i in range ( MAX_CHAR ) ] ; NEW_LINE eval ( expr1 , v , True ) ; NEW_LINE eval ( expr2 , v , False ) ; NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( v [ i ] != 0 ) : NEW_LINE return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT expr1 = " - ( a + b + c ) " NEW_LINE expr2 = " - a - b - c " ; NEW_LINE if ( areSame ( expr1 , expr2 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT