-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathevaluate_reverse_polish_notation.py
More file actions
52 lines (43 loc) · 1.41 KB
/
evaluate_reverse_polish_notation.py
File metadata and controls
52 lines (43 loc) · 1.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
"""
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
"""
def evaluate_reverse_polish_notation(tokens):
"""
Returns the result of evaluation of an arithmetic expression in Reverse Polish Notation
:param tokens: Array of tokens that for Reverse Polish Notation
:return: result of the expression
"""
def __add(stack):
right_operand = stack.pop()
left_operand = stack.pop()
return left_operand + right_operand
def __subtract(stack):
right_operand = stack.pop()
left_operand = stack.pop()
return left_operand - right_operand
def __multiply(stack):
right_operand = stack.pop()
left_operand = stack.pop()
return left_operand * right_operand
def __divide(stack):
right_operand = stack.pop()
left_operand = stack.pop()
return int(round(left_operand / right_operand))
stack = []
operations = {
"+": __add,
"-": __subtract,
"*": __multiply,
"/": __divide,
}
for token in tokens:
if token in operations:
result = operations[token](stack)
stack.append(result)
else:
stack.append(int(token))
if len(stack) == 1:
return stack.pop()
else:
raise ValueError("invalid expression")