Python time limit exceeded


  • 1
    S

    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]

  • 1
    S

    Please do not print in your code.


  • 0
    S

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


  • 0
    S

    How about this one print stack?


  • 1
    X

    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


  • 0
    S

    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.


  • 0
    J

    Yes it is. I'm also using python, I got problem about this testcase
    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.


  • 0
    E

    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.


  • 0
    D

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


Log in to reply
 

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