add postfix solns
This commit is contained in:
24
0150_evaluate-reverse-polish-notation/python3/solution.py
Normal file
24
0150_evaluate-reverse-polish-notation/python3/solution.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import math
|
||||
from collections import deque
|
||||
|
||||
class Solution:
|
||||
def evalRPN(self, tokens: List[str]) -> int:
|
||||
compute = {
|
||||
'+': lambda a, b: a + b,
|
||||
'-': lambda a, b: a - b,
|
||||
'*': lambda a, b: a * b,
|
||||
'/': lambda a, b: math.trunc(a / b)
|
||||
}
|
||||
|
||||
stack = deque()
|
||||
|
||||
for token in tokens:
|
||||
if token.lstrip('-').isdigit():
|
||||
stack.append(int(token))
|
||||
else:
|
||||
right = stack.pop()
|
||||
left = stack.pop()
|
||||
|
||||
stack.append(compute[token](left, right))
|
||||
|
||||
return stack[-1]
|
||||
Reference in New Issue
Block a user