Reverse Polish Notation (RPN), also called postfix notation, places operators after operands. It removes the need for parentheses and operator-precedence rules, making it efficient for stack-based evaluation.
Given a valid RPN expression containing integers and the operators +, -, *, /, compute its final value. Where:
- Operands may be positive or negative integers
- Division truncates toward zero
- No division by zero will occur
- The expression always evaluates to an integer result
For Example:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Python Implementation
A stack is used to evaluate the RPN expression by processing tokens one by one. Operands are stored, and operators compute results using the last two values.
tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
stack = []
for token in tokens:
if token not in {"+", "-", "*", "/"}:
stack.append(int(token))
else:
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
elif token == "/":
stack.append(int(left / right))
print("Value of the expression =", stack.pop())
Output
Value of the expression = 22
Explanation:
- stack stores operands during evaluation.
- for token in tokens: iterates through each element of the RPN expression.
- if token not in {"+", "-", "*", "/"} checks whether the token is an operand.
- stack.append(int(token)) pushes the operand onto the stack.
- right = stack.pop() and left = stack.pop() retrieve the last two operands.
- Arithmetic operations (+, -, *, /) are applied based on the operator.
- int(left / right) ensures division truncates toward zero.
- stack.pop() at the end gives the final evaluated result.