Using eval() for shorter code stack = [] # stack contains strings for c in tokens: if c in '+-*/': b, a = stack.pop(), stack.pop() stack.append(str(int(eval(a + c + b)))) else: stack.append(c) return int(stack[0])
Pay attention, in Python 2, the / operator performs integer division, and rounds towards negative infinity. So 6/-132 gives -1, and of course int(6/-132) also gives -1. In Python 3, the / operator performs float division, so 6/-132 is -0.045. Then the int function truncates decimals, so int(6/-132) is 0.
Hello there, when putting the condition for the token being a number in the if and it being an operator in the else part, why was there a problem with the pop() statement, error said as "pop from an empty list", ? Has it got something to do with the interpreter ? Although it works fine in vs code
Master Data Structures & Algorithms For FREE at AlgoMap.io!
Best channel I’ve discovered this year! Great content, thank you
Using eval() for shorter code
stack = [] # stack contains strings
for c in tokens:
if c in '+-*/':
b, a = stack.pop(), stack.pop()
stack.append(str(int(eval(a + c + b))))
else:
stack.append(c)
return int(stack[0])
Could you not use stk.append( int(a / b) ) for division instead of the if/else and use of ceil and floor?
I didnt know int() would do all that for you
you can, it works
Pay attention, in Python 2, the / operator performs integer division, and rounds towards negative infinity. So 6/-132 gives -1, and of course int(6/-132) also gives -1. In Python 3, the / operator performs float division, so 6/-132 is -0.045. Then the int function truncates decimals, so int(6/-132) is 0.
Hello there, when putting the condition for the token being a number in the if and it being an operator in the else part, why was there a problem with the pop() statement, error said as "pop from an empty list", ? Has it got something to do with the interpreter ?
Although it works fine in vs code
I feel that this statement in the question is the most important. "The division between two integers always truncates toward zero."
Great content and dedication.
Ceil and floor giving error in leetcode although in my local compiler the output is correct.
Try this instead:
int(float(a)/b)
or just simply int(a / b). a / b already gives us a float, therefore converting a to float explicitly is not required.
For js/ ts ceil doesn't work i think i had to use trunc ..
Noticed that in Java implementation you also used ceil and floor. But it is redundant for integer division. It always drops the part after dot.
or we can just append int(a/b)