Skip to content

Commit 38f0073

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 227 Basic Calculator II
1 parent ffe438f commit 38f0073

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
4848
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
4949
- [219 Contains Duplicates II](https://leetcode.com/problems/contains-duplicate-ii/description/)
5050
- [224 Basic Calculator](https://leetcode.com/problems/basic-calculator/description/)
51+
- [227 Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/description/)
5152
- [228 Summary Ranges](https://leetcode.com/problems/summary-ranges/description/)
5253
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
5354
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution:
2+
def calculate(self, s: str) -> int:
3+
"""
4+
Given a string s which represents an expression,
5+
evaluate this expression and return its value.
6+
7+
The integer division should truncate toward zero.
8+
9+
You may assume that the given expression is always valid.
10+
All intermediate results will be in the range of [-231, 231 - 1].
11+
12+
Note: You are not allowed to use any built-in function which
13+
evaluates strings as mathematical expressions, such as eval().
14+
"""
15+
prev, cur, res, op, i = 0, 0, 0, "+", 0
16+
while i < len(s):
17+
c = s[i]
18+
if c.isdigit():
19+
while i < len(s) and s[i].isdigit():
20+
cur = cur * 10 + int(s[i])
21+
i += 1
22+
i -= 1
23+
if op == "+":
24+
res += cur
25+
prev = cur
26+
elif op == "-":
27+
res -= cur
28+
prev = -cur
29+
elif op == "*":
30+
res -= prev
31+
res += prev * cur
32+
prev = cur * prev
33+
elif op == "/":
34+
res -= prev
35+
res += int(prev / cur)
36+
prev = int(prev / cur)
37+
38+
cur = 0
39+
elif c != " ":
40+
op = c
41+
i += 1
42+
return res

tests/test_227_basic_calculator_II.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._227_basic_calculator_II import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["s", "expected"],
8+
argvalues=[
9+
("3+2*2", 7),
10+
(" 3/2 ", 1),
11+
(" 3+5 / 2 ", 5),
12+
],
13+
)
14+
def test_func(s: str, expected: int):
15+
result = Solution().calculate(s)
16+
assert result == expected

0 commit comments

Comments
 (0)