human
Minimum number of bracket reversals needed to make an expression balanced | Set | 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 ..
To store number of reversals required ..
To store number of unbalanced opening brackets ..
To store number of unbalanced closing brackets ..
If current bracket is open then increment open count ..
If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket ..
For the case : " " or when one closing and one opening bracket remains for pairing , then both need to be reversed ..
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 ) :
	length = len ( expr )
	if length % 2 :
		return - 1
	ans = 0
	open = 0
	close = 0
	for i in range ( 0 , length ) :
		if expr [ i ] == " " :
			open += 1
		else :
			if not open :
				close += 1
			else :
				open -= 1
	ans = ( close // 2 ) + ( open // 2 )
	close %= 2
	open %= 2
	if close > 0 :
		ans += 2
	return ans
if __name__ == " _ _ main _ _ " :
	expr = " } } { { "
	print ( countMinReversals ( expr ) )