Floor or ceil the result all get error in python

  • 0

    class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
    operator={"+":(lambda x,y : x+y), "-":(lambda x,y : x-y), "":(lambda x,y : xy), "/": (lambda x,y: x/y)}
    for e in tokens:
    if e not in operator.keys():
    if e in operator.keys():
    return int(a[0])

    can not pass the test
    Input: ["10","6","9","3","+","-11","","/","","17","+","5","+"]
    Output: 21
    Expected: 22

    if I change to return int(round(a[0]))
    it can not pass the test
    Input: ["4","13","5","/","+"]
    Output: 7
    Expected: 6

    any one can help me have a look at it?
    I think the test criteria is awkward.

  • 2

    Keep in mind that this problem, as well as many others on this website, uses only integer arithmetics. So only returning the final result as an int is not enough, you need to make sure that in EVERY STEP, the result is always an integer (the integral part of the actual result).

  • 1

    This is due to negative integer division problem in python 2.x. In python 2.x, if you do -1/3, the result will be -1 instead of 0. Python 3 actually fixes this problem.

    For this particular code, you may just want to use abs() to do positive number integer division and determine the sign afterwards.

Log in to reply

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