Skip to content

Commit ab09c1f

Browse files
authored
Update basic-calculator.py
1 parent 8c2e813 commit ab09c1f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Python/basic-calculator.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,47 @@
11
# Time: O(n)
22
# Space: O(n)
33

4+
import operator
5+
46

57
class Solution(object):
8+
def calculate(self, s):
9+
"""
10+
:type s: str
11+
:rtype: int
12+
"""
13+
def compute(operands, operators):
14+
right, left = operands.pop(), operands.pop()
15+
operands.append(ops[operators.pop()](left, right))
16+
17+
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
18+
precedence = {'+':0, '-':0, '*':1, '/':1}
19+
operands, operators, operand = [], [], 0
20+
for i in xrange(len(s)):
21+
if s[i].isdigit():
22+
operand = operand*10 + int(s[i])
23+
if i == len(s)-1 or not s[i+1].isdigit():
24+
operands.append(operand)
25+
operand = 0
26+
elif s[i] == '(':
27+
operators.append(s[i])
28+
elif s[i] == ')':
29+
while operators[-1] != '(':
30+
compute(operands, operators)
31+
operators.pop()
32+
elif s[i] in precedence:
33+
while operators and operators[-1] in precedence and \
34+
precedence[operators[-1]] >= precedence[s[i]]:
35+
compute(operands, operators)
36+
operators.append(s[i])
37+
while operators:
38+
compute(operands, operators)
39+
return operands[-1]
40+
41+
42+
# Time: O(n)
43+
# Space: O(n)
44+
class Solution2(object):
645
# @param {string} s
746
# @return {integer}
847
def calculate(self, s):

0 commit comments

Comments
 (0)