forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-calculator-ii.py
More file actions
executable file
·31 lines (28 loc) · 1.05 KB
/
basic-calculator-ii.py
File metadata and controls
executable file
·31 lines (28 loc) · 1.05 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
class Solution(object):
def calculate(self, s):
s += '+' #edge case, for last operation to be executed.
lastOperation = '+' #edge case, for the first currNum
operations = set(['+', '-', '*', '/'])
stack = []
currNum = 0
for c in s:
if c.isdigit():
currNum = currNum*10 + int(c)
elif c in operations:
if lastOperation=='+':
stack.append(currNum)
currNum = 0
elif lastOperation=='-':
stack.append(-currNum)
currNum = 0
elif lastOperation=='*':
currNum = stack.pop() * currNum
stack.append(currNum)
currNum = 0
elif lastOperation=='/':
currNum = stack.pop() / currNum
if currNum<0: currNum += 1
stack.append(currNum)
currNum = 0
lastOperation = c
return sum(stack)