mycode 42.30%、
Note: If the symbol is not considered, -1 = -1 // 3 instead equal to 0, because it is rounded down
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ from collections import deque def cal(data_1,data_2,item): if item == '/': return abs(data_2) // abs(data_1) *(-1 if (data_2 > 0) ^ (data_1 > 0) else 1) elif item == '+': return data_2 + data_1 elif item == '-': return data_2 - data_1 else: return data_2 * data_1 dq = deque() calset = ['/','+','-','*'] for item in tokens: if item in calset: #print('if') data_1 = dq.pop() data_2 = dq.pop() data = cal(int(data_1),int(data_2),item) dq.append(data) else: #print('else') dq.append(item) #print(dq) return dq[0]
reference:
# Https://www.cnblogs.com/zuoyuan/p/3760530.html Note negative division, c ++ and pytho distinction class Solution: # @param tokens, A List of String # @return AN Integer DEF evalRPN (Self, tokens): Stack = [] for I in Range (0, len (tokens)): IF ! tokens [I] = ' + ' and ! tokens [I] = ' - ' and ! tokens [I] = ' * ' and tokens [I] =! ' / ' : stack.append(int(tokens[i])) else: a = stack.pop() b = stack.pop() if tokens[i] == '+': stack.append(a+b) if tokens[i] == '-': stack.append(b-a) if tokens[i] == '*': stack.append(a*b) if tokens[i] == '/': if a*b < 0: stack.append(-((-b)/a)) else: stack.append(b/a) return stack.pop()