-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0227__basic_calcualtor_2.py
More file actions
64 lines (50 loc) · 1.57 KB
/
0227__basic_calcualtor_2.py
File metadata and controls
64 lines (50 loc) · 1.57 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
LeetCode: https://leetcode.com/problems/basic-calculator-ii/description/
"""
from operator import add, mul, floordiv, sub
from unittest import TestCase
class Solution(TestCase):
def test_example_1(self):
self.assertEqual(7, self.calculate("3+2*2"))
def test_example_2(self):
self.assertEqual(1, self.calculate(" 3/2 "))
def test_example_3(self):
self.assertEqual(5, self.calculate(" 3+5 / 2 "))
def test_case_77(self):
self.assertEqual(0, self.calculate("1-1"))
def test_case_103(self):
self.assertEqual(13, self.calculate("14-3/2"))
def calculate(self, s: str) -> int:
op_map = {
'+': add,
'*': mul,
'/': floordiv,
'-': sub,
}
stack = []
buf = []
ptr = 0
op = '+'
while ptr < len(s):
while ptr < len(s) and s[ptr] not in op_map.keys():
if s[ptr].isdigit():
buf.append(s[ptr])
ptr += 1
num = int("".join(buf))
buf = []
if op == '*':
num = stack.pop() * num
elif op == '/':
num = int(stack.pop() / num)
if op == '-':
stack.append(-num)
else:
stack.append(num)
while ptr < len(s) and s[ptr] == ' ':
ptr += 1
if ptr < len(s):
op = s[ptr]
ptr += 1
while len(stack) > 1:
stack.append(stack.pop() + stack.pop())
return stack[-1]