Calculate score of parentheses from a given string | Function to calculate the score of the parentheses using stack ; To keep track of the score ; Initially , push 0 to stack ; Traverse the string s ; If ' ( ' is encountered , then push 0 to stack ; Otherwise ; Balance the last ' ( ' , and store the score of inner parentheses ; If tmp is not zero , it means inner parentheses exists ; Otherwise , it means no inner parentheses exists ; Pass the score of this level to parent parentheses ; Print the score ; Driver Code ; Function call
def scoreOfParentheses ( s ) : NEW_LINE INDENT stack = [ ] NEW_LINE stack . append ( 0 ) NEW_LINE for c in s : NEW_LINE INDENT if ( c == ' ( ' ) : NEW_LINE INDENT stack . append ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT tmp = stack [ len ( stack ) - 1 ] NEW_LINE stack = stack [ : - 1 ] NEW_LINE val = 0 NEW_LINE if ( tmp > 0 ) : NEW_LINE INDENT val = tmp * 2 NEW_LINE DEDENT else : NEW_LINE INDENT val = 1 NEW_LINE DEDENT stack [ len ( stack ) - 1 ] += val NEW_LINE DEDENT DEDENT print ( stack [ len ( stack ) - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ( ( ) ( ( ) ) ) " NEW_LINE scoreOfParentheses ( S ) NEW_LINE DEDENT