Evaluate Reverse Polish Notation

2018-05-15  本文已影响0人  GakkiLove

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Assumption

Valid operators are +, -, *, /.
Each operand may be an integer or another expression.

Examples

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

class Solution(object):
  def evalRPN(self, tokens):
    stack = []
    for item in tokens:
      if item not in ("+","-","*","/"):
        stack.append(int(item))
      else:
        a = stack.pop()
        b = stack.pop()
        if item == '+':
          stack.append(a+b)
        if item == '-':
          stack.append(b-a)
        if item == '*':
          stack.append(b*a)
        if item == '/':
          if a*b < 0:
            stack.append(-((-b)/a))
          else:
            stack.append(b/a)
    return stack.pop()
上一篇下一篇

猜你喜欢

热点阅读