Using Python 2.7
I was trying to solve the Reverse Polish Notation problem on LeetCodeOJ.
I wrote my straightforward solution in Python as follows:
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token in ["+" , "-" ,"*", "/"]:
op1 = stack.pop()
op2 = stack.pop()
if token == "+":
stack.append(op2+op1)
elif token == "-":
stack.append(op2-op1)
elif token == "*":
stack.append(op2*op1)
elif token == "/":
stack.append(op2/op1)
else:
stack.append(int(token))
if len(stack) == 1:
return stack.pop()
else:
return 0
This gets rejected on a test case:
Input: ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 12
Expected: 22
But if I modify the application of '/' operation to stack.append(int(op2 / (op1*1.0))), it succeeds.
The / operation is performed once on this input calculating 6/-132 which results in -1 using either of two ways.
Strangely, despite the fact that both evaluations result in -1, the program as a whole differs in its output. As shown above, using the first way gives 12 as the RPNEval while using the second would give 22.
What causes this?
I visited this link, but it only says that there is some difference in the / operator in Python and C++. What is the difference?