topic
Evaluate the expression according to reverse Polish notation.
Valid operators include +, -, *, /. Each operand can be an integer or another reverse Polish expression.
illustrate:
Integer division only retains the integer part.
The given reverse Polish expression is always valid. In other words, the expression always evaluates to a valid value and there is no divisor by zero.
Example 1:
Import: [“2”, “1”, “+”, “3”, “*”]
Export: 9
Unsolved : ((2 + 1) * 3) = 9
Example 2:
Import: [“4”, “13”, “5”, “/”, “+”]
Export: 6
Solution : (4 + (13 / 5)) = 6
Example 3:
Import: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
Output: 22
Solution:
((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
Ideas
Traverse the array tokens. If a non-operator is encountered, push it onto the stack. If an operator is encountered, pop up the top two elements of the stack for calculation, and then push the calculation result onto the stack.
Code that runs successfully
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = list()
operations = {
'+', '-', '*', '/'}
for token in tokens:
if token in operations:
right = stack.pop()
left = stack.pop()
if token == '+':
tmp = left + right
elif token == '-':
tmp = left - right
elif token == '*':
tmp = left * right
else:
if left * right >= 0:
tmp = left // right
else:
tmp = -(-left // right)
stack.append(tmp)
else:
stack.append(int(token))
return stack[0]