-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path227 Basic Calculator II.py
109 lines (87 loc) · 2.62 KB
/
227 Basic Calculator II.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
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division
should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.
Author: Rajeev Ranjan
"""
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
lst = self.parse(s)
post = self.infix2postfix(lst)
return self.eval_postfix(post)
def parse(self, s):
"""
return tokens
"""
i = 0
ret = []
while i < len(s):
if s[i] == " ":
i += 1
elif s[i] in ("(", ")", "+", "-", "*", "/"):
ret.append(s[i])
i += 1
else:
b = i
while i < len(s) and s[i].isdigit():
i += 1
ret.append(s[b:i])
return ret
def infix2postfix(self, lst):
# operator stacks rather than operand
stk = [] # stk only stores operators in strictly increasing precedence
ret = []
for elt in lst:
if elt.isdigit():
ret.append(elt)
elif elt == "(":
stk.append(elt)
elif elt == ")":
while stk[-1] != "(":
ret.append(stk.pop())
stk.pop()
else: # generalized to include * and /
while stk and self.precendece(elt) <= self.precendece(stk[-1]):
ret.append(stk.pop())
stk.append(elt)
while stk:
ret.append(stk.pop())
return ret
def precendece(self, op):
if op in ("(", ")"):
return 0
if op in ("+", "-"):
return 1
if op in ("*", "/"):
return 2
return 3
def eval_postfix(self, post):
stk = []
for elt in post:
if elt in ("+", "-", "*", "/"):
b = int(stk.pop())
a = int(stk.pop())
if elt == "+":
stk.append(a+b)
elif elt == "-":
stk.append(a-b)
elif elt == "*":
stk.append(a*b)
else:
stk.append(a/b)
else:
stk.append(elt)
assert len(stk) == 1
return int(stk[-1])
if __name__ == "__main__":
assert Solution().calculate("3+2*2") == 7