-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsol_Basic_Calculator.py
More file actions
170 lines (138 loc) · 3.31 KB
/
Copy pathsol_Basic_Calculator.py
File metadata and controls
170 lines (138 loc) · 3.31 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
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
"""
Example 1:
Input: "1 + 1"
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
"""
class Solution:
conv1 = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
}
conv2 = {
0: '0',
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
}
order = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
'!': 0,
}
def str2int(self, s):
_sum = i = 0
_s = list(s)
neg = None
if _s[0] == '-':
neg = _s.pop(0)
_len = len(_s)
for j in range(_len):
_sum += Solution.conv1[_s[_len - j - 1]] * (10 ** i)
i += 1
if neg:
return -_sum
return _sum
def int2str(self, val):
s = ''
if val == 0:
return '0'
_val = val
if _val < 0:
_val = -_val
while _val:
v = _val % 10
s = Solution.conv2[v] + s
_val //= 10
if val < 0:
return '-' + s
return s
def cal(self, expr):
word = ''
opts = []
nums = []
_expr = list(expr)
_expr.append('!')
ng = False
for c in _expr:
if c == ' ':
if word != '':
nums.append(self.str2int(word))
word = ''
elif c in ['+', '-', '*', '/', '!']:
if word:
n = self.str2int(word)
if ng:
n = -n
ng = False
nums.append(n)
word = ''
elif c == '-':
# 处理负数
if not nums:
opts.append('+')
ng = True
continue
while len(nums) >= 2 and opts and Solution.order[opts[-1]] >= Solution.order[c]:
opt = opts.pop(-1)
r = nums.pop(-1)
l = nums.pop(-1)
if opt == '+':
val = l + r
elif opt == '-':
val = l - r
elif opt == '*':
val = l * r
else:
val = l // r
nums.append(val)
opts.append(c)
else:
word += c
return nums[0]
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
words = []
_s = list(s)
_s.append(')')
_s.insert(0, '(')
for c in _s:
if c == ')':
expr = ''
while words:
w = words.pop(-1)
if w == '(':
result = self.cal(expr)
words.append(self.int2str(result))
break
expr = w + expr
else:
words.append(c)
return self.str2int(words[0])
sol = Solution()
ret = sol.calculate('1+2*-11')
print(ret)