-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBasicCaculator_v1.py
More file actions
47 lines (41 loc) · 1.17 KB
/
BasicCaculator_v1.py
File metadata and controls
47 lines (41 loc) · 1.17 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
#!/usr/bin/env python
# encoding: utf-8
class Solution:
# @param {string} s
# @return {integer}
def calculate(self, s):
number = 0
symbol = 1
result = 0
stack = []
for c in s:
if c.isdigit():
number = number * 10 + int(c)
elif c == '+':
result += symbol * number
symbol = 1
number = 0
elif c == '-':
result += symbol * number
symbol = -1
number = 0
elif c == '(':
stack.append(symbol)
stack.append(result)
symbol = 1
result = 0
elif c == ')':
result += symbol * number
_result = stack.pop()
_symbol = stack.pop()
result = _symbol*result + _result
number = 0
if number:
result += symbol * number
return result
if __name__ == '__main__':
s = Solution()
print s.calculate('1 + 1')
print s.calculate(' 2-1 + 2 ')
print s.calculate('(1+(4+5+2)-3)+(6+8)')
print s.calculate('2-(5-6)')