human
Minimum number of bracket reversals needed to make an expression balanced | Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced ..
length of expression must be even to make it balanced by using reversals ..
After this loop , stack contains unbalanced part of expression , i . e . , expression of the form " . . . . ".
Length of the reduced expression red_len = ( m + n ).
count opening brackets at the end of stack.
return ceil ( m / 2 ) + ceil ( n / 2 ) which is actually equal to ( m + n ) / 2 + n % 2 when m + n is even ..
Driver Code"
Solution in Python:
assistant
#Here is code to minimum number of bracket reversals needed to make an expression balanced and the other steps required.
 def countMinReversals ( expr ) :
	lenn = len ( expr )
	if ( lenn % 2 ) :
		return - 1
	s = [ ]
	for i in range ( lenn ) :
		if ( expr [ i ] == ' ' and len ( s ) ) :
			if ( s [ 0 ] == ' ' ) :
				s . pop ( 0 )
			else :
				s . insert ( 0 , expr [ i ] )
		else :
			s . insert ( 0 , expr [ i ] )
	red_len = len ( s )
	n = 0
	while ( len ( s ) and s [ 0 ] == ' ' ) :
		s . pop ( 0 )
		n += 1
	return ( red_len // 2 + n % 2 )
if __name__ == ' _ _ main _ _ ' :
	expr = " } } { { "
	print ( countMinReversals ( expr . strip ( ) ) )