1
# Runtime: 62 ms (Top 83.61%) | Memory: 14.1 MB (Top 62.30%)4
self, exp: Optional[str] = "", *, term: Optional[Mapping[str, int]] = {}6
self.d = defaultdict(int, **term)7
if re.match(r"^\-?\d+$", exp):12
def __add__(self, other: "Term") -> "Term":13
return self._pm(other, add=True)15
def __mul__(self, other: "Term") -> "Term":16
res = defaultdict(int)17
for (l_var, l_coef), (r_var, r_coef) in product(18
self.d.items(), other.d.items()20
res["*".join(sorted(self._exp(l_var) + self._exp(r_var)))] += (25
def __sub__(self, other: "Term") -> "Term":26
return self._pm(other, add=False)28
def get(self) -> List[str]:30
str(coef) + "*" * bool(var) + var31
for var, coef in sorted(32
self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])37
def _exp(self, var: str) -> List[str]:38
return list(filter(bool, var.split("*")))40
def _pm(self, other: "Term", *, add: bool) -> "Term":41
res = copy.copy(self.d)42
for var, coef in other.d.items():43
res[var] += coef * (-1) ** (1 - add)48
def basicCalculatorIV(49
self, expression: str, evalvars: List[str], evalints: List[int]51
vals = dict(zip(evalvars, evalints))55
lambda m: "Term('" + str(vals.get(m.group(), m.group())) + "')",