Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN).
Valid operators are +
, -
, *
, and /
. Each operand may be an integer or another expression.
Note:
Examples:
["2","1","+","3","*"]
, Output: 9
["4","13","5","/","+"]
, Output: 6
["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
, Output: 22
def evalRPN(tokens):
stack = []
for token in tokens:
if token in "+-*/":
# Pop the top two elements from the stack
b = stack.pop()
a = stack.pop()
# Perform the operation
if token == "+":
result = a + b
elif token == "-":
result = a - b
elif token == "*":
result = a * b
elif token == "/":
# Python's division needs to be truncated towards zero
result = int(a / b)
# Push the result back onto the stack
stack.append(result)
else:
# Push the number onto the stack
stack.append(int(token))
# The result is the last element in the stack
return stack[0]
# Example usage
print(evalRPN(["2", "1", "+", "3", "*"])) # Expected output: 9
print(evalRPN(["4", "13", "5", "/", "+"])) # Expected output: 6
print(evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"])) # Expected output: 22
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?