Calculate sum of the array generated by given operations | Function to find the sum of the array formed by performing given set of operations while traversing the array ops [ ] ; If the size of array is 0 ; Stores the required sum ; Traverse the array ops [ ] ; If the character is C , remove the top element from the stack ; If the character is D , then push 2 * top element into stack ; If the character is + , add sum of top two elements from the stack ; Otherwise , push x and add it to ans ; Print the resultant sum ; Driver Code
def findTotalSum ( ops ) : NEW_LINE INDENT if ( len ( ops ) == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT pts = [ ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ( ops ) ) : NEW_LINE INDENT if ( ops [ i ] == " C " ) : NEW_LINE INDENT ans -= pts [ - 1 ] NEW_LINE pts . pop ( ) NEW_LINE DEDENT elif ( ops [ i ] == " D " ) : NEW_LINE INDENT pts . append ( pts [ - 1 ] * 2 ) NEW_LINE ans += pts [ - 1 ] NEW_LINE DEDENT elif ( ops [ i ] == " + " ) : NEW_LINE INDENT a = pts [ - 1 ] NEW_LINE pts . pop ( ) NEW_LINE b = pts [ - 1 ] NEW_LINE pts . append ( a ) NEW_LINE ans += ( a + b ) NEW_LINE pts . append ( a + b ) NEW_LINE DEDENT else : NEW_LINE INDENT n = int ( ops [ i ] ) NEW_LINE ans += n NEW_LINE pts . append ( n ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ "5" , " - 2" , " C " , " D " , " + " ] NEW_LINE findTotalSum ( arr ) NEW_LINE DEDENT