-
Notifications
You must be signed in to change notification settings - Fork 17
/
basic-calculator.py
230 lines (179 loc) · 6.81 KB
/
basic-calculator.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import string
from enum import Enum
from typing import List, Optional, Tuple, Union
class Operation(Enum):
ADD = 0
SUBSTRACT = 1
class ExpressionTreeNodeType(Enum):
OPERATION = 0
CONSTANT = 0
class ExpressionTreeNode:
def __init__(
self,
node_type: ExpressionTreeNodeType,
value: Optional[int],
operation: Optional[Operation],
) -> None:
self.node_type = node_type
self.value = value
self.operation = operation
self.left: Optional[ExpressionTreeNode] = None
self.right: Optional[ExpressionTreeNode] = None
class Solution1:
def calculate(self, expression: str) -> int:
def get_number(pos: int) -> Tuple[int, int]:
number = 0
offset = 0
while expression[pos] in string.digits:
number *= 10
number += int(expression[pos])
offset += 1
pos += 1
return offset, number
def calculate(sub_expression: List[Union[int, str]]) -> int:
result = 0
sign = 1
for val in sub_expression:
if isinstance(val, int):
result += sign * val
elif val == "+":
sign = 1
elif val == "-":
sign = -1
return result
expression = "(" + expression + ")"
stack: List[Union[int, str]] = []
pos = 0
while pos < len(expression):
if expression[pos] == " ":
pos += 1
elif expression[pos] == "(":
pos += 1
stack.append("(")
elif expression[pos] == ")":
pos += 1
tmp: List[Union[int, str]] = []
while stack[-1] != "(":
tmp.append(stack.pop())
tmp.reverse()
number = calculate(tmp)
stack.pop()
stack.append(number)
elif expression[pos] == "+":
pos += 1
stack.append("+")
elif expression[pos] == "-":
pos += 1
stack.append("-")
else:
offset, number = get_number(pos)
stack.append(number)
pos += offset
return int(stack[-1])
class Calculator:
def __init__(self) -> None:
pass
def _get_integer(self, pos: int, expression: str) -> Tuple[int, int]:
result = 0
while pos < len(expression) and expression[pos].isdigit():
result *= 10
result += int(expression[pos])
pos += 1
return pos, result
def _get_subtree(self, pos: int, expression: str) -> Tuple[int, ExpressionTreeNode]:
if expression[pos] == "(":
return self._parse(pos + 1, expression)
else:
pos, constant = self._get_integer(pos, expression)
return (
pos,
ExpressionTreeNode(ExpressionTreeNodeType.CONSTANT, constant, None),
)
def _parse(self, pos: int, expression: str) -> Tuple[int, ExpressionTreeNode]:
pos, left = self._get_subtree(pos, expression)
while expression[pos] in "+-":
operation = Operation.ADD if expression[pos] == "+" else Operation.SUBSTRACT
pos, right = self._get_subtree(pos + 1, expression)
node = ExpressionTreeNode(ExpressionTreeNodeType.OPERATION, None, operation)
node.left = left
node.right = right
left = node
pos += 1
return pos, left
def _calculate(self, node: ExpressionTreeNode) -> int:
if (
node.node_type == ExpressionTreeNodeType.OPERATION
and node.left
and node.right
):
if node.operation == Operation.ADD:
return self._calculate(node.left) + self._calculate(node.right)
else:
return self._calculate(node.left) - self._calculate(node.right)
else:
if node.value is None:
raise ValueError("Constant node value cannot be None")
return node.value
def calculate(self, expression: str) -> int:
expression = "(" + expression.replace(" ", "") + ")"
_, node = self._get_subtree(0, expression)
return self._calculate(node)
def _parse_expression(self, expression: str) -> List[Union[str, int]]:
pos = 0
result: List[Union[str, int]] = []
while pos < len(expression):
if expression[pos] in "-+()":
result.append(expression[pos])
pos += 1
elif expression[pos][0].isdigit():
pos, number = self._get_integer(pos, expression)
result.append(number)
else:
pos += 1
return result
def calculate2(self, expression: str) -> int:
parsed_expression = self._parse_expression(expression)
prefix_stack: List[Union[str, int]] = []
operator_stack: List[Union[str, int]] = []
pos = 0
for pos in range(len(parsed_expression)):
if isinstance(parsed_expression[pos], int):
prefix_stack.append(int(parsed_expression[pos]))
elif str(parsed_expression[pos]) in "+-":
while operator_stack and operator_stack[-1] == "-":
prefix_stack.append(operator_stack.pop())
operator_stack.append(parsed_expression[pos])
elif parsed_expression[pos] == "(":
operator_stack.append(parsed_expression[pos])
elif parsed_expression[pos] == ")":
while operator_stack and operator_stack[-1] != "(":
prefix_stack.append(operator_stack.pop())
operator_stack.pop()
else:
raise NotImplementedError("Type of input is not supported")
while operator_stack:
prefix_stack.append(operator_stack.pop())
stack: List[Union[str, int]] = []
for value in reversed(prefix_stack):
stack.append(value)
while len(stack) > 2:
operation, right, left = stack[-3:]
if (
str(operation) in "-+"
and isinstance(left, int)
and isinstance(right, int)
):
stack.pop()
stack.pop()
stack.pop()
if operation == "+":
stack.append(left + right)
else:
stack.append(left - right)
else:
break
return int(stack.pop())
class Solution:
def calculate(self, s: str) -> int:
calculator = Calculator()
return calculator.calculate2(s)