Title: Evaluate Reverse Polish Notation Source: leetcode.com
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
1 2 |
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 |
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
''' https://leetcode.com/problems/evaluate-reverse-polish-notation/ ''' class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ num_stack = [] for token in tokens: if token == '+': num2 = num_stack.pop() num1 = num_stack.pop() num_stack.append(num1 + num2) elif token == '-': num2 = num_stack.pop() num1 = num_stack.pop() num_stack.append(num1 - num2) elif token == '*': num2 = num_stack.pop() num1 = num_stack.pop() num_stack.append(num1 * num2) elif token == '/': num2 = num_stack.pop() num1 = num_stack.pop() num_stack.append(int(float(num1) / num2)) else: num_stack.append(int(token)) #print num_stack return int(num_stack[0]) |