-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path224 Basic Calculator.py
99 lines (79 loc) · 2.42 KB
/
224 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
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
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers
and empty spaces.
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
Author: Rajeev Ranjan
"""
class Solution:
def calculate(self, s):
"""
* infix to postfix
* eval postfix
:type s: str
:rtype: int
"""
lst = self.to_list(s)
postfix = self.infix2postfix(lst)
return self.eval_postfix(postfix)
def to_list(self, s):
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):
stk = [] # store 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
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)
else:
stk.append(a-b)
else:
stk.append(elt)
assert len(stk) == 1
return int(stk[-1])
if __name__ == "__main__":
assert Solution().calculate(" 2-1 + 2 ") == 3
assert Solution().calculate("(1+(4+5+2)-3)+(6+8)") == 23