Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def from_terms_dict(terms_dict):
"""For internal use."""
return Expr(tuple(Term(k, v) for k, v in terms_dict.items() if v))
def __sub__(self, other):
if isinstance(other, Number):
other = Expr.from_number(other)
elif isinstance(other, Term):
other = Expr.from_term(other)
if isinstance(other, Expr):
terms = self.terms_to_dict()
for op, coeff in other.terms:
if op in terms:
terms[op] -= coeff
if terms[op] == 0:
del terms[op]
else:
terms[op] = -coeff
return Expr.from_terms_dict(terms)
return NotImplemented
def __rmul__(self, other):
if isinstance(other, Number):
if other == 0:
return Expr.from_number(0.0)
return Expr.from_terms_iter(Term(op, coeff * other) for op, coeff in self.terms)
if isinstance(other, _PauliImpl):
other = other.to_term()
if isinstance(other, Term):
return Expr(tuple(other * term for term in self.terms))
return NotImplemented
def __truediv__(self, other):
if isinstance(other, Number):
if other:
return Expr(tuple(term / other for term in self.terms))
raise ZeroDivisionError
return NotImplemented
def simplify(self):
"""Simplify the Expr."""
d = defaultdict(float)
for term in self.terms:
term = term.simplify()
d[term.ops] += term.coeff
return Expr.from_terms_iter(
Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k])
def from_terms_iter(terms):
"""For internal use."""
return Expr(tuple(term for term in terms if term.coeff))