当前位置 : 主页 > 网络编程 > lua >

leetcode-mid-others-150. Evaluate Reverse Polish Notation

来源:互联网 收集:自由互联 发布时间:2021-06-23
mycode 42.30%、 注意:如果不考虑符号,-1//3=-1而不是等于0,因为是向下取整 class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ from collections import deque def cal(data_1,d

mycode   42.30%、

注意:如果不考虑符号,-1//3=-1而不是等于0,因为是向下取整

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]

 

参考:

#https://www.cnblogs.com/zuoyuan/p/3760530.html  注意负数的除法,c++和pytho的区别
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()
网友评论