Evaluate Reverse Polish Notation Leetcode Python

来源:互联网 发布:docker hub 阿里云 编辑:程序博客网 时间:2024/06/04 22:48
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


We need to use an extra stack to solve this problem.

1.append all the none symbol values to the stack,

the pop two element everytime and then take sum/deduct/multiply/divide 


the code is as follow:

class Solution:    # @param tokens, a list of string    # @return an integer    def evalRPN(self, tokens):        stack=[]        for index in range(len(tokens)):            if tokens[index]!='+' and tokens[index]!='-' and tokens[index]!='*' and tokens[index]!='/':                stack.append(int(tokens[index]))            else:                a=int(stack.pop())                b=int(stack.pop())                if tokens[index]=='+':                    stack.append(a+b)                if tokens[index]=='-':                    stack.append(b-a)                if tokens[index]=='*':                    stack.append(a*b)                if tokens[index]=='/':                    if a*b<0:                        stack.append(-(-b/a))                    else:                        stack.append(b/a)        return stack.pop()


0 0
原创粉丝点击