Evaluate Reverse Polish Notation submit result is wrong ?


  • 0
    W

    my code of python

    class Solution:
        # @param tokens, a list of string
        # @return an integer
        def evalRPN(self, List):
            if len(List) < 3:
                return int(List[0])
            operate = ['+','-','*','/']
            x = 0
            y = 0
            number = []
            for a in List:
                if a in operate:
                    y = number.pop()
                    x=  number.pop()
                    number.append(self.__oprate(a,x,y))
                else:
                    number.append(int(a))
            return number[0]
    
        def __oprate(self,op,x,y):
            if op == '+':
                return x + y
            elif op == '-':
                return  x - y
            elif op == '*':
                return x * y
            elif op == '/':
                if y == 0:
                    return 0
                else:
                    return int(x / y)
            else:
                return 0
    

    Submission Result: Wrong Answer

    Input: ["10","6","9","3","+","-11","","/","","17","+","5","+"]

    Output: 12

    Expected: 22

    But in my computer output is 22,why?
    somebody can review my code and tell me why?


  • 4
    Y

    I have the exact same result as you have. I double check all intermediate results and also python doc, the reason why the python version does not go for 22 is because:

    `In Python, '/' integer division function always rounded towards minus infinit [https://docs.python.org/2/library/stdtypes.html]. This means '6/-132=-1' in Python instead of 0. Consequently, in Python we have 10 *(-1) +17 + 5 = 12.


  • 0
    C

    Thank you very much! I had the same problem with python.


  • 0
    L

    Does it mean that we can never pass using python?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.