Remove brackets from an algebraic string containing + and | Function to simplify the String ; resultant String of max Length equal to Length of input String ; create empty stack ; If top is 1 , flip the operator ; If top is 0 , append the same operator ; x is opposite to the top of stack ; append value equal to top of the stack ; If closing parentheses pop the stack once ; copy the character to the result ; Driver Code
def simplify ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE res = [ None ] * Len NEW_LINE index = 0 NEW_LINE i = 0 NEW_LINE s = [ ] NEW_LINE s . append ( 0 ) NEW_LINE while ( i < Len ) : NEW_LINE INDENT if ( Str [ i ] == ' + ' ) : NEW_LINE INDENT if ( s [ - 1 ] == 1 ) : NEW_LINE INDENT res [ index ] = ' - ' NEW_LINE index += 1 NEW_LINE DEDENT if ( s [ - 1 ] == 0 ) : NEW_LINE INDENT res [ index ] = ' + ' NEW_LINE index += 1 NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' - ' ) : NEW_LINE INDENT if ( s [ - 1 ] == 1 ) : NEW_LINE INDENT res [ index ] = ' + ' NEW_LINE index += 1 NEW_LINE DEDENT elif ( s [ - 1 ] == 0 ) : NEW_LINE INDENT res [ index ] = ' - ' NEW_LINE index += 1 NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' ( ' and i > 0 ) : NEW_LINE INDENT if ( Str [ i - 1 ] == ' - ' ) : NEW_LINE INDENT x = 0 if ( s [ - 1 ] == 1 ) else 1 NEW_LINE s . append ( x ) NEW_LINE DEDENT elif ( Str [ i - 1 ] == ' + ' ) : NEW_LINE INDENT s . append ( s [ - 1 ] ) NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' ) ' ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ index ] = Str [ i ] NEW_LINE index += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " a - ( b + c ) " NEW_LINE s2 = " a - ( b - c - ( d + e ) ) - f " NEW_LINE r1 = simplify ( s1 ) NEW_LINE for i in r1 : NEW_LINE INDENT if i != None : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE r2 = simplify ( s2 ) NEW_LINE for i in r2 : NEW_LINE INDENT if i != None : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT