Number of closing brackets needed to complete a regular bracket sequence | Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then answer is impossible ; If possible , print ' s ' and required closing brackets . ; Driver code
def completeSequence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE open = 0 NEW_LINE close = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT open += 1 NEW_LINE DEDENT else : NEW_LINE INDENT close += 1 NEW_LINE DEDENT if ( close > open ) : NEW_LINE INDENT print ( " IMPOSSIBLE " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( s , end = " " ) NEW_LINE for i in range ( open - close ) : NEW_LINE INDENT print ( " ) " , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ( ( ) ( ( ) ( " NEW_LINE completeSequence ( s ) NEW_LINE DEDENT