逆波兰式 (2018-10-31)

原文(https://blog.csdn.net/zhangla1220/article/details/39060421)

题目:

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

代码:

def caculate(oper, x, y):
    if oper== '+' :
            return x+y
    if oper== '-' :
            return x-y
    if oper== '*' :
            return x*y
    if oper== '/' :
            return x/y
   
def evalRPN(tokens):
    if (len(tokens) == 0):
        return 0;
    tokens_s = []
    result = 0
    i = 0;
    x = 0
    y = 0
    for i in range(0,len(tokens)):
        element = tokens[i] 
        if ((element== "+") or (element== "-") or (element== "*") or (element== "/")):
            y = tokens_s.pop()
            x = tokens_s.pop()
            tokens_s.append(int(caculate(element,int(x),int(y))))
        else:
            tokens_s.append(int(element))
    return (int)(tokens_s.pop())
tokens =  []#test
print(evalRPN(tokens))
tokens =  ["2", "1", "+", "3", "*"]#test
print(evalRPN(tokens))

你可能感兴趣的:(逆波兰式 (2018-10-31))