My accepted Python solution after eliminate the division bugs


  • 0

    Division has some bugs in Python, so my first submission get Wrong Answer, after evaluate the bugs, it works well!

    class Solution:
        # @param tokens, a list of string
        # @return an integer
        def evalRPN(self, tokens):
            nums = []
            for each in tokens:
                if each in ["+", "-", "*", "/"]:
                    num1 = nums.pop()
                    num2 = nums.pop()
                    if each == "+":
                        nums.append(num2 + num1)
                    else:
                        if each == "-":
                            nums.append(num2 - num1)
                        else:
                            if each == "*":
                                nums.append(num2 * num1)
                            else:
                                if each == "/":
                                    # Eliminate the Python division bugs
                                    if num2 * num1 < 0 and num2 % num1:
                                        nums.append(num2 / num1 + 1)
                                    else:
                                        nums.append(num2 / num1)
                else:
                    nums.append(int(each))
            return nums.pop()

  • 1
    D

    yes, at first I got the division problem. My code is below. but this the division problem isn't a bug. python
    design it like that. below is my code.

    class Solution:
        # @param tokens, a list of string
        # @return an integer
        def evalRPN(self, tokens):
            operation = {}
            operation['/'] = lambda x,y:int(float(x)/y)
            operation['+'] = lambda x,y:x+y
            operation['-'] = lambda x,y:x-y
            operation['*'] = lambda x,y:x*y
    
            numStack = []
            
            index = 0
            while  index < len(tokens):
                value = tokens[index]
                # print value
                if operation.has_key(value):
                    y = numStack.pop()
                    x = numStack.pop()
                    result = operation[value](x, y)
                    numStack.append(result)
                    print "push : " + str(x) + value + str(y) + '=' + str(result)
                else:
                    numStack.append(int(value))
                index +=1
            return numStack.pop()
    

Log in to reply
 

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