-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_calculator.py
55 lines (44 loc) · 1.31 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
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def evaluate_stack(stack):
res = stack.pop()
while stack:
c = stack.pop()
if c == ")":
break
elif c == "+":
c = stack.pop()
res += c
elif c == "-":
c = stack.pop()
res -= c
else:
res += c
return res
i = len(s) - 1
stack = list()
sign = 1
res = 0
n = 0
num = 0
while i >= 0:
if s[i].isdigit():
num += (10 ** n * int(s[i]))
n += 1
elif s[i] != " ":
if n:
stack.append(num)
num, n = 0, 0
if s[i] != "(":
stack.append(s[i])
if s[i] == "(":
res = evaluate_stack(stack)
stack.append(res)
i -= 1
if n:
stack.append(num)
return evaluate_stack(stack)