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?