-
Notifications
You must be signed in to change notification settings - Fork 0
/
227_basic_calculator_ii.py
82 lines (76 loc) · 2.68 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
'''
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.
'''
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def evaluate(num1, num2, op):
if op == '+':
return num1+num2
if op == '-':
return num1-num2
if op == '*':
return num1*num2
if op == '/':
return num1/num2
def priority(op):
return 2 if op == '*' or op == '/' else 1
i = 0
operands = []
operators = []
while i < len(s):
ch = s[i]
if ord('0') <= ord(ch) <= ord('9'):
num = 0
while ord('0') <= ord(ch) <= ord('9'):
num = 10 * num + int(ch)
i += 1
if i >= len(s):
break
ch = s[i]
operands.append(num)
continue
elif ch == '(':
operators.append(ch)
elif ch == ')':
while operators[-1] != '(':
result = evaluate(operands[-2], operands[-1], operators[-1])
del operators[-1]
del operands[-1]
del operands[-1]
operands.append(result)
del operators[-1]
elif ch == '+' or ch == '-' or ch == '*' or ch == '/':
while len(operators) > 0 and operators[-1] != '(' and priority(ch) <= priority(operators[-1]):
result = evaluate(operands[-2], operands[-1], operators[-1])
del operators[-1]
del operands[-1]
del operands[-1]
operands.append(result)
operators.append(ch)
i += 1
# print operators, operands
while len(operators) > 0:
result = evaluate(operands[-2], operands[-1], operators[-1])
del operators[-1]
del operands[-1]
del operands[-1]
operands.append(result)
return operands[0]
s = Solution()
assert s.calculate("1 + 1") == 2
assert s.calculate(" 2-1 + 2 ") == 3
assert s.calculate("(1+(4+5+2)-3)+(6+8)") == 23
assert s.calculate("3+2*2") == 7
assert s.calculate(" 3/2 ") == 1
assert s.calculate(" 3+5 / 2 ") == 5