1. 程式人生 > >150. Evaluate Reverse Polish Notation(逆波蘭表達式)

150. Evaluate Reverse Polish Notation(逆波蘭表達式)

逆波蘭 逆波蘭表達式 spa rpn href self desc quest tor

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:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

 1 class
Solution: 2 def evalRPN(self, tokens): 3 """ 4 :type tokens: List[str] 5 :rtype: int 6 """ 7 stack = [] 8 for i in tokens: 9 if i not in [+,-,*,/]: 10 stack.append(i) 11 else: 12 v2 = int(stack.pop())
13 v1 = int(stack.pop()) 14 if i==+: 15 stack.append(v1+v2) 16 if i==-: 17 stack.append(v1-v2) 18 if i==*: 19 stack.append(v1*v2) 20 if i==/: 21 stack.append(v1/v2)
22 return int(stack[0]) 23

150. Evaluate Reverse Polish Notation(逆波蘭表達式)