-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc772.py
More file actions
66 lines (60 loc) · 1.71 KB
/
lc772.py
File metadata and controls
66 lines (60 loc) · 1.71 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
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
# first define a couple helper methods
# operation helper to perform basic math operations
def operation(op, second, first):
if op == "+":
return first + second
elif op == "-":
return first - second
elif op == "*":
return first * second
elif op == "/": # integer division
return first // second
# calculate the relative precedence of the the operators "()" > "*/" > "+="
# and determine if we want to do a pre-calculation in the stack
# (when current_op is <= op_from_ops)
def precedence(current_op, op_from_ops):
if op_from_ops == "(" or op_from_ops == ")":
return False
if (current_op == "*" or current_op == "/") and (op_from_ops == "+" or op_from_ops == "-"):
return False
return True
if not s:
return 0
# define two stack: nums to store the numbers and ops to store the operators
nums, ops = [], []
i = 0
while i < len(s):
c = s[i]
if c == " ":
i += 1
continue
elif c.isdigit():
num = int(c)
while i < len(s) - 1 and s[i + 1].isdigit():
num = num * 10 + int(s[i + 1])
i += 1
nums.append(num)
elif c == "(":
ops.append(c)
elif c == ")":
# do the math when we encounter a ')' until '('
while ops[-1] != "(":
nums.append(operation(ops.pop(), nums.pop(), nums.pop()))
ops.pop()
elif c in ["+", "-", "*", "/"]:
while len(ops) != 0 and precedence(c, ops[-1]):
nums.append(operation(ops.pop(), nums.pop(), nums.pop()))
ops.append(c)
i += 1
while len(ops) > 0:
nums.append(operation(ops.pop(), nums.pop(), nums.pop()))
return nums.pop()
a = Solution()
s = "2*(5+5*2)/3+(6/2+8)"
print(a.calculate(s))