Modify a numeric string to a balanced parentheses by replacements | Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Given Input ; Function Call
def balBracketSequence ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( str [ 0 ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( " No " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen = 0 NEW_LINE cntForClose = 0 NEW_LINE check = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT elif str [ i ] == str [ n - 1 ] : NEW_LINE INDENT cntForOpen -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT if ( cntForOpen < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForOpen == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT cntForClose += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForClose -= 1 NEW_LINE DEDENT if ( cntForClose < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForClose == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT DEDENT print ( " NO " , end = " " ) NEW_LINE DEDENT DEDENT str = "123122" NEW_LINE balBracketSequence ( str ) NEW_LINE