-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_calculator_III.py
64 lines (52 loc) · 1.65 KB
/
basic_calculator_III.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
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def evaluate_stack(stack):
res = 0
num = 0
while stack:
c = stack.pop()
if c == ")":
break
elif c == "+":
res += num
num = stack.pop()
elif c == "-":
res += num
num = (-1) * stack.pop()
elif c == "*":
num *= stack.pop()
elif c == "/":
#print num
if num < 0:
num = ((-1) * num / stack.pop()) * (-1)
else: num /= stack.pop()
#print num
else:
num = c
return res + num
i = len(s) - 1
stack = list()
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)