美文网首页
Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

作者: GakkiLove | 来源:发表于2018-05-15 20:15 被阅读0次

    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()
    

    相关文章

      网友评论

          本文标题:Evaluate Reverse Polish Notation

          本文链接:https://www.haomeiwen.com/subject/fgiydftx.html