File tree Expand file tree Collapse file tree 3 files changed +47
-0
lines changed Expand file tree Collapse file tree 3 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -47,6 +47,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
4747- [ 202 Happy Number] ( https://leetcode.com/problems/happy-number/description/ )
4848- [ 205 Isomorphic Strings] ( https://leetcode.com/problems/isomorphic-strings/description/ )
4949- [ 219 Contains Duplicates II] ( https://leetcode.com/problems/contains-duplicate-ii/description/ )
50+ - [ 224 Basic Calculator] ( https://leetcode.com/problems/basic-calculator/description/ )
5051- [ 228 Summary Ranges] ( https://leetcode.com/problems/summary-ranges/description/ )
5152- [ 242 Valid Anagram] ( https://leetcode.com/problems/valid-anagram/description/ )
5253- [ 290 Word Pattern] ( https://leetcode.com/problems/word-pattern/description/ )
Original file line number Diff line number Diff line change 1+ class Solution :
2+ def calculate (self , s : str ) -> int :
3+ """
4+ Given a string s representing a valid expression,
5+ implement a basic calculator to evaluate it,
6+ and return the result of the evaluation.
7+
8+ Note: You are not allowed to use any built-in function
9+ which evaluates strings as mathematical
10+ expressions, such as eval().
11+ """
12+ stack = []
13+ cur , res , sign = 0 , 0 , 1
14+ for c in s :
15+ if c .isdigit ():
16+ cur = cur * 10 + int (c )
17+ elif c in ["+" , "-" ]:
18+ res += sign * cur
19+ cur = 0
20+ sign = 1 if c == "+" else - 1
21+ elif c == "(" :
22+ stack .append ((res , sign ))
23+ res , sign = 0 , 1
24+ elif c == ")" :
25+ res += sign * cur
26+ i_res , i_sign = stack .pop ()
27+ res *= i_sign
28+ res += i_res
29+ cur = 0
30+ return res + sign * cur
Original file line number Diff line number Diff line change 1+ import pytest
2+
3+ from awesome_python_leetcode ._224_basic_calculator import Solution
4+
5+
6+ @pytest .mark .parametrize (
7+ argnames = ["s" , "expected" ],
8+ argvalues = [
9+ ("1 + 1" , 2 ),
10+ (" 2-1 + 2 " , 3 ),
11+ ("(1+(4+5+2)-3)+(6+8)" , 23 ),
12+ ],
13+ )
14+ def test_func (s : str , expected : int ):
15+ result = Solution ().calculate (s )
16+ assert result == expected
You can’t perform that action at this time.
0 commit comments