-
Notifications
You must be signed in to change notification settings - Fork 2
/
150.py
50 lines (44 loc) · 1.45 KB
/
150.py
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
# [ LeetCode ] 150. Evaluate Reverse Polish Notation
def solution(tokens: list[str]) -> int:
def get_calculate_result(left: int, right: int, operator: str) -> int:
if operator == "+":
return left + right
if operator == "-":
return left - right
if operator == "*":
return left * right
return int(left / right)
OPERATORS: set[str] = {"+", "-", "*", "/"}
stack: list[int] = []
for token in tokens:
if token in OPERATORS:
right: int = stack.pop()
left: int = stack.pop()
result: int = get_calculate_result(left, right, token)
stack.append(result)
else:
number: int = int(token)
stack.append(number)
answer: int = stack.pop()
return answer
if __name__ == "__main__":
cases: list[dict[str, dict[str, list[str]] | int]] = [
{
"input": { "tokens": ["2","1","+","3","*"] },
"output": 9
},
{
"input": { "tokens": ["4","13","5","/","+"] },
"output": 6
},
{
"input": {
"tokens": [
"10","6","9","3","+","-11","*","/","*","17","+","5","+"
]
},
"output": 22
}
]
for case in cases:
assert case["output"] == solution(**case["input"])