> ## 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 IV Python Solution with Tests

> Tested Python solution for LeetCode 770 with 21 pytest cases. Generate a practice environment with lcpy.

LeetCode 770, [Hard](/catalog/hard). Topics: [Hash Table](/catalog/topics/hash-table), [Math](/catalog/topics/math), [String](/catalog/topics/string), [Stack](/catalog/topics/stack), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/basic-calculator-iv/description/).

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

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

## Problem

Given an expression such as `expression = "e + 8 - a + 5"` and an evaluation map such as `{"e": 1}` (given in terms of `evalvars = ["e"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `["-1*a","14"]`

* An expression alternates chunks and symbols, with a space separating each chunk and symbol.
* A chunk is either an expression in parentheses, a variable, or a non-negative integer.
* A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x"` or `"-x"`.

Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.

* For example, `expression = "1 + 2 * 3"` has an answer of `["7"]`.

The format of the output is as follows:

* For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.

  * For example, we would never write a term like `"b*a*c"`, only `"a*b*c"`.

* Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.

  * For example, `"a*a*b*c"` has degree `4`.

* The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.

* An example of a well-formatted answer is `["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]`.

* Terms (including constant terms) with coefficient `0` are not included.

  * For example, an expression of `"0"` has an output of `[]`.

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

### Examples

```
Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]
```

```
Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]
```

```
Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]
```

### Constraints

* 1 \<= expression.length \<= 250
* expression consists of lowercase English letters, digits, '+', '-', '\*', '(', ')', and ' '.
* expression does not contain any leading or trailing spaces.
* All the tokens in expression are separated by a single space.
* 0 \<= evalvars.length \<= 100
* 1 \<= evalvars\[i].length \<= 20
* evalvars\[i] consists of lowercase English letters.
* evalints.length == evalvars.length
* -100 \<= evalints\[i] \<= 100

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

Poly = dict[tuple[str, ...], int]


class Solution:
    # Time: O(n * m) where n is the expression length and m the term count
    # Space: O(n + m)
    def basic_calculator_iv(
        self, expression: str, evalvars: list[str], evalints: list[int]
    ) -> list[str]:
        sub = dict(zip(evalvars, evalints, strict=True))
        tokens = deque(self._tokenize(expression))
        poly = self._expression(tokens, sub)
        return self._format(poly)

    @staticmethod
    def _tokenize(expression: str) -> list[str]:
        tokens: list[str] = []
        for chunk in expression.split(" "):
            opens = 0
            while chunk.startswith("("):
                opens += 1
                chunk = chunk[1:]
            closes = 0
            while chunk.endswith(")"):
                closes += 1
                chunk = chunk[:-1]
            tokens.extend(["("] * opens)
            if chunk:
                tokens.append(chunk)
            tokens.extend([")"] * closes)
        return tokens

    @staticmethod
    def _add(left: Poly, right: Poly, sign: int) -> Poly:
        result = dict(left)
        for term, coeff in right.items():
            updated = result.get(term, 0) + sign * coeff
            if updated:
                result[term] = updated
            else:
                result.pop(term, None)
        return result

    @staticmethod
    def _mul(left: Poly, right: Poly) -> Poly:
        result: Poly = {}
        for left_term, left_coeff in left.items():
            for right_term, right_coeff in right.items():
                term = tuple(sorted(left_term + right_term))
                result[term] = result.get(term, 0) + left_coeff * right_coeff
        return {term: coeff for term, coeff in result.items() if coeff}

    def _expression(self, tokens: deque[str], sub: dict[str, int]) -> Poly:
        poly = self._term(tokens, sub)
        while tokens and tokens[0] in ("+", "-"):
            sign = 1 if tokens.popleft() == "+" else -1
            poly = self._add(poly, self._term(tokens, sub), sign)
        return poly

    def _term(self, tokens: deque[str], sub: dict[str, int]) -> Poly:
        poly = self._factor(tokens, sub)
        while tokens and tokens[0] == "*":
            tokens.popleft()
            poly = self._mul(poly, self._factor(tokens, sub))
        return poly

    def _factor(self, tokens: deque[str], sub: dict[str, int]) -> Poly:
        token = tokens.popleft()
        if token == "(":
            poly = self._expression(tokens, sub)
            tokens.popleft()  # matching closing paren
            return poly
        if token.isdigit():
            return {(): int(token)} if int(token) else {}
        if token in sub:
            return {(): sub[token]} if sub[token] else {}
        return {(token,): 1}

    @staticmethod
    def _format(poly: Poly) -> list[str]:
        ordered = sorted(poly.items(), key=lambda item: (-len(item[0]), item[0]))
        return [str(coeff) + ("*" + "*".join(term) if term else "") for term, coeff in ordered]
```

## Complexity

| Time | Space |
| - | - |
| O(n \* m) where n is the expression length and m the term count | O(n + m) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.