> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Basic Calculator II Python Solution with Tests

> Tested Python solution for LeetCode 227 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 227, Medium. Topics: Math, String, Stack. [View on LeetCode](https://leetcode.com/problems/basic-calculator-ii/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 227   # by problem number
lcpy gen -s basic_calculator_ii   # by problem name
```

## Problem

Given a string `s` which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of \[-2^31, 2^31 - 1].

**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.

### Examples

```
Input: s = "3+2*2"
Output: 7
```

```
Input: s = " 3/2 "
Output: 1
```

```
Input: s = " 3+5 / 2 "
Output: 5
```

### Constraints

* 1 \<= s.length \<= 3 \* 10^5
* s consists of integers and operators ('+', '-', '\*', '/') separated by some number of spaces.
* s represents a valid expression.
* All the integers in the expression are non-negative integers in the range \[0, 2^31 - 1].
* The answer is guaranteed to fit in a 32-bit integer.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/basic_calculator_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/basic_calculator_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n) — single pass
    # Space: O(n) — stack of operands
    def calculate(self, s: str) -> int:
        stack: list[int] = []
        current = 0
        op = "+"

        def apply(value: int) -> None:
            nonlocal stack
            if op == "+":
                stack.append(value)
            elif op == "-":
                stack.append(-value)
            elif op == "*":
                stack.append(stack.pop() * value)
            else:  # "/"
                prev = stack.pop()
                # Truncate toward zero
                stack.append(int(prev / value))

        for ch in s:
            if ch.isdigit():
                current = current * 10 + int(ch)
            elif ch in "+-*/":
                apply(current)
                op = ch
                current = 0

        apply(current)  # last operand
        return sum(stack)
```

## Complexity

| Time               | Space                    |
| ------------------ | ------------------------ |
| O(n) — single pass | O(n) — stack of operands |

## Tags

[Grind](/catalog/grind), [NeetCode All](/catalog/neetcode).
