# Program to check final answer by performing given stack operations in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of string called ops where each element is any one of these operations like below −

• A non-negative integer value that will be pushed into a stack
• "POP" to delete top most element from the stack
• "DUP" to insert top element again into the stack, to make it duplicate
• "+" to pop out the top two elements and push the sum value
• "-" to pop out the top two elements and push the result of (top element - element just below top)

So we have to find the top mot element in the stack after applying all of these operations. If some operations are not valid then return -1.

So, if the input is like ops = ["5", "2", "POP", "DUP", "3", "+", "15", "-"], then the output will be 7 because initially using first two operations, insert 5 and 2 so stack is like [5, 2], then pop one so current stack is like . After that for DUP, the 5 will be duplicated, so stack is like [5, 5], then add 3 [5, 5, 3], then for addition operation it will be [5, 8], then insert 15, so [5, 8, 15] after that for subtract operation the stack will be [5, (15-8)] = [5, 7]. So top most element is 7.

To solve this, we will follow these steps −

• stack := a new stack
• for each i in ops, do
• if i is a number, then
• push i into stack
• otherwise when size of stack >= 1 and i is "POP", then
• pop top element from stack
• otherwise when size of stack >= 1 and i is same as "DUP", then
• pop top-most element from stack into p
• and insert p twice
• otherwise when size of stack >= 2 and i is same as "+", then
• pop top-most element from stack into a
• pop top-most element from stack into b
• push (a + b) into stack
• otherwise when size of stack >= 2 and i is same as "-", then
• pop top-most element from stack into a
• pop top-most element from stack into b
• push (a - b) into stack
• otherwise,
• return -1

## Example

Let us see the following implementation to get better understanding −

def solve(ops):
stack = []
for i in ops:
if i.isnumeric() == True:
stack.append(int(i))
elif len(stack) >= 1 and i == "POP":
stack.pop()
elif len(stack) >= 1 and i == "DUP":
p = stack.pop()
stack.append(p)
stack.append(p)
elif len(stack) >= 2 and i == "+":
a = stack.pop()
b = stack.pop()
stack.append(a + b)
elif len(stack) >= 2 and i == "-":
a = stack.pop()
b = stack.pop()
stack.append(a - b)
else:
return -1
return stack.pop()

ops = ["5", "2", "POP", "DUP", "3", "+", "15", "-"]
print(solve(ops))

## Input

["5", "2", "POP", "DUP", "3", "+", "15", "-"]

## Output

7