-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_reverse_polish_notation.py
More file actions
59 lines (46 loc) · 2.41 KB
/
Copy pathevaluate_reverse_polish_notation.py
File metadata and controls
59 lines (46 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from typing import List
class Solution:
"""LeetCode #150 - Evaluate Reverse Polish Notation (Medium)
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Evaluate an expression in postfix (Reverse Polish) notation, where the
operator follows its operands: ["2", "1", "+", "3", "*"] means (2 + 1) * 3.
"""
@staticmethod
def _divide(a: int, b: int) -> int:
"""Integer division that truncates toward zero, as the problem requires.
This is the classic trap here. Python's // rounds *down*:
-7 // 2 == -4 but the expected answer is -3.
Computing the magnitude first and re-applying the sign gives the C-style
truncation the problem asks for.
The popular shortcut `int(a / b)` also truncates toward zero, but it
routes through a float and would lose precision on very large operands.
"""
quotient = abs(a) // abs(b)
return -quotient if (a < 0) != (b < 0) else quotient
def evalRPN(self, tokens: List[str]) -> int:
"""Stack evaluation - one pass, no parsing of parentheses needed.
Key insight: postfix notation is unambiguous precisely because the
operands of an operator are always the two most recent results. That is
LIFO order, so a stack evaluates the whole expression in one pass, and
no precedence rules or brackets are involved at all.
Order matters when popping: the *second* pop is the left operand, since
it was pushed first. Getting that backwards silently breaks - and * only.
Time: O(n) - one push or one pop-pop-push per token.
Space: O(n) - the stack, at most the number of operands.
"""
stack = []
for token in tokens:
if token in ("+", "-", "*", "/"):
right = stack.pop() # pushed last -> right operand
left = stack.pop() # pushed first -> left operand
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
else:
stack.append(self._divide(left, right))
else:
stack.append(int(token)) # int() also handles "-11"
return stack[-1] # a valid expression leaves exactly one value