Skip to content

Commit 862db64

Browse files
committed
Runtime: 62 ms (Top 83.61%) | Memory: 14.1 MB (Top 62.30%)
1 parent 6c9051e commit 862db64

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,31 @@
1+
# Runtime: 62 ms (Top 83.61%) | Memory: 14.1 MB (Top 62.30%)
12
class Term:
23
def __init__(self, exp: Optional[str]='', *, term: Optional[Mapping[str, int]]={}) -> None:
34
self.d = defaultdict(int, **term)
45
if re.match(r'^\-?\d+$', exp):
56
self.d[''] += int(exp)
67
elif exp:
78
self.d[exp] += 1
8-
9+
910
def __add__(self, other: 'Term') -> 'Term':
1011
return self._pm(other, add=True)
11-
12+
1213
def __mul__(self, other: 'Term') -> 'Term':
1314
res = defaultdict(int)
1415
for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):
1516
res['*'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef
1617
return Term(term=res)
17-
18+
1819
def __sub__(self, other: 'Term') -> 'Term':
1920
return self._pm(other, add=False)
2021

2122
def get(self) -> List[str]:
2223
return [str(coef)+'*'*bool(var)+var \
2324
for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]
24-
25+
2526
def _exp(self, var: str) -> List[str]:
2627
return list(filter(bool, var.split('*')))
27-
28+
2829
def _pm(self, other: 'Term', *, add: bool) -> 'Term':
2930
res = copy.copy(self.d)
3031
for var, coef in other.d.items():
@@ -34,4 +35,4 @@ def _pm(self, other: 'Term', *, add: bool) -> 'Term':
3435
class Solution:
3536
def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:
3637
vals = dict(zip(evalvars, evalints))
37-
return eval(re.sub(r'[a-z0-9]+', lambda m: "Term('"+str(vals.get(m.group(), m.group()))+"')", expression)).get()
38+
return eval(re.sub(r'[a-z0-9]+', lambda m: "Term('"+str(vals.get(m.group(), m.group()))+"')", expression)).get()

0 commit comments

Comments
 (0)