Which version of python interpreter is it for OJ?


  • 0
    T

    I used Python 2.7.5 on my desktop to test my code against the case:
    ["10","6","9","3","+","-11","","/","","17","+","5","+"]
    The result yields to 22. But when submit with the same code, the result is 21 and will not pass.
    Here's my code for desktop tests:

    # @param tokens, a list of string
    # @return an integer
    def evalRPN(tokens):
        if tokens == None or len(tokens) == 0:
            return None
        stack = []
        #assume all strings in tokens are integers or operators
        for i in tokens:
            if i not in ["+", "-", "*", "/"]:
                stack.append(int(i))
                print stack, ", %s pushed" % i
            else:
                op2 = stack.pop()
                print stack, ", %f poped" % op2
                op1 = stack.pop()
                print stack, ", %f poped" % op1
                if i == "+":
                    stack.append(op1 + op2)
                elif i == "-":
                    stack.append(op1 - op2)
                elif i == "*":
                    stack.append(op1 * op2)
                elif i == "/":
                    stack.append(op1 / float(op2))
                else: 
                    return None
                print stack
        return int(round(stack.pop()))
    
    input1 = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
    input2 = ["4","13","5","/","+"]
    print evalRPN(input1)

  • 2
    A

    In elif i=="/":
    stack.append(op1/float(op2)) You should add the "int()",let the result of division Integer.
    So,it should be this,

    stack.append(int(op1/float(op2)))


  • 0
    J

    can there be detailed explaination about why we need to use int(op1/float(op2)) instead of just op1/op2?


  • 0
    A

    What this done is to avoid the op1<0 or op2 <0


  • 1
    Z
    class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        alist = []
        for index,item in enumerate(tokens):
            if(item.lstrip('-').isdigit()):
                alist.append(item)
                continue
            tmp = str(int(eval(str(float(alist[-2]))+ item +alist[-1])))
            alist.pop()
            alist.pop()
            alist.append(tmp)
        return int(alist[0])
    

    Just for your reference .


  • 0
    Z

    thanks for your info.


Log in to reply
 

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