Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to check final answer by performing given stack operations in Python
Suppose we have a list of strings called ops where each element represents one of these stack operations ?
- A non-negative integer value that will be pushed onto the stack
- "POP" to delete the topmost element from the stack
- "DUP" to duplicate the top element and push it onto the stack
- "+" to pop the top two elements and push their sum
- "-" to pop the top two elements and push the result of (top element − second element)
We need to find the topmost element in the stack after applying all operations. If any operation is invalid (insufficient elements), return -1.
Problem Example
If the input is ops = ["5", "2", "POP", "DUP", "3", "+", "15", "-"], let's trace through the operations ?
- Push 5, Push 2 ? Stack: [5, 2]
- POP ? Stack: [5]
- DUP ? Stack: [5, 5]
- Push 3 ? Stack: [5, 5, 3]
- + (pop 3 and 5, push 8) ? Stack: [5, 8]
- Push 15 ? Stack: [5, 8, 15]
- - (pop 15 and 8, push 15-8=7) ? Stack: [5, 7]
The topmost element is 7.
Algorithm
The approach follows these steps ?
- Initialize an empty stack
- For each operation in the list:
- If it's a number, push it onto the stack
- If it's "POP" and stack has ?1 element, pop the top
- If it's "DUP" and stack has ?1 element, duplicate the top
- If it's "+" and stack has ?2 elements, pop two and push sum
- If it's "-" and stack has ?2 elements, pop two and push difference
- Otherwise, return -1 (invalid operation)
- Return the top element
Implementation
def solve(ops):
stack = []
for operation in ops:
if operation.isnumeric():
stack.append(int(operation))
elif len(stack) >= 1 and operation == "POP":
stack.pop()
elif len(stack) >= 1 and operation == "DUP":
top = stack.pop()
stack.append(top)
stack.append(top)
elif len(stack) >= 2 and operation == "+":
a = stack.pop()
b = stack.pop()
stack.append(a + b)
elif len(stack) >= 2 and operation == "-":
a = stack.pop()
b = stack.pop()
stack.append(a - b)
else:
return -1
return stack.pop() if stack else -1
# Test with the example
ops = ["5", "2", "POP", "DUP", "3", "+", "15", "-"]
result = solve(ops)
print(f"Result: {result}")
Result: 7
Edge Cases
Let's test some edge cases to verify our solution ?
# Test cases
test_cases = [
(["1", "2", "+"], 3), # Simple addition
(["5", "DUP", "-"], 0), # 5-5 = 0
(["10", "POP"], -1), # Empty stack at end
(["+"], -1), # Invalid operation
(["3", "POP", "DUP"], -1), # DUP on empty stack
]
for i, (ops, expected) in enumerate(test_cases):
result = solve(ops)
status = "?" if result == expected else "?"
print(f"Test {i+1}: {ops} ? {result} {status}")
Test 1: ['1', '2', '+'] ? 3 ? Test 2: ['5', 'DUP', '-'] ? 0 ? Test 3: ['10', 'POP'] ? -1 ? Test 4: ['+'] ? -1 ? Test 5: ['3', 'POP', 'DUP'] ? -1 ?
Key Points
- Always check stack size before performing operations
- For subtraction, order matters:
a - bwhereais the top element - Handle edge cases like empty stack operations
- Use
isnumeric()to identify integer strings
Conclusion
This stack-based calculator processes operations sequentially, validating each step. The key is checking stack size before operations and handling edge cases properly to return -1 for invalid sequences.
Advertisements
