when I do Leetcode questions I write the code in PyCharm on my PC and when it's working I copy paste it into Leetcode.
This is the code I have written.
def main():
# tokens = ["2", "1", "+", "3", "*"]
# tokens = ["4", "13", "5", "/", "+"]
tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
print(eval_rpn(tokens))
def eval_rpn(tokens):
stack = []
ops = ["+", "-", "*", "/"]
for c in tokens:
if c not in ops:
stack.append(c)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if c == "+":
total = num1 + num2
elif c == "-":
total = num1 - num2
elif c == "*":
total = num1 * num2
else: # The only operator left is division
total = num1 / num2
stack.append(total)
return stack[-1]
if __name__ == "__main__":
main()
This is the code I have pasted and submitted in Leetcode.
class Solution(object):
def evalRPN(self, tokens):
stack = []
ops = ["+", "-", "*", "/"]
for c in tokens:
if c not in ops:
stack.append(c)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if c == "+":
total = num1 + num2
elif c == "-":
total = num1 - num2
elif c == "*":
total = num1 * num2
else:
total = num1 / num2
stack.append(total)
return stack[-1]
But for some reason for the input tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Leetcode returns 12. When I run the same code on my PC it returns 22. 22 is the expected output. Not 12.
Can anyone point out what I am doing wrong?
This is happening because of different version(Python 2.7) you might have selected in leetcode editor
And this is happening because of the way how python 2.7 handles negative number division , if you follow your code you will see at one point the value in stack would be -132 and then the subsequent division with 6 is making the result as -1
print 6/-132 # results in -1
For detailed explanation see this Negative integer division surprising result
This behaviour is handled in python3 and if you change your editor version to python3 it will work as expected.