# Python time limit exceeded

• Below is my code and I don't know what is causing it to exceed the time limit, is there a more efficient way to do it?

``````class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = [];
for item in tokens:
print stack
if item.isdigit():
stack.append(int(item))
elif item[1:].isdigit() and item[0]=="-":
stack.append(int(item))
else:
num2 = stack.pop()
num1 = stack.pop()
if item == "+":
stack.append(num1+num2)
elif item == "-":
stack.append(num1-num2)
elif item == "*":
stack.append(num1*num2)
elif item == "/":
stack.append(num1/num2)
else:
print "symbol not recognized"

return stack[0]``````

• The print statement is just in case of invalid input, if the input is valid, there should not be anything printed

• How about this one `print stack`?

• Hi shunji,

Did you get your code accepted in python? I found that python has a really different way in processing division when negative numbers involved, I had submitted two solutions, one in python and the other in c++, those sharing the same algorithm, but I got an accepted in c++ but a wrong answer in python. LOL

Best,
Xiangyang

• Yes, I got mine accepted in java first and then in python. Just comment out the above print stack line and I think it would be fine.

Input: ["10","6","9","3","+","-11","","/","","17","+","5","+"]

Expected: 22

In python, 6 / -132 = -1. But in C++, the output is 0. That's the difference.

• You are right, python has a different division mechanism. -6/7 = -1 instead of 0. Thus same algorithm in Java has a different result in Python, my Python code did not get accepted either.

• I got the same issue. Removing print statement really helps me. Thx.

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