"""Polynomials in named variables with rational coefficients (standard library only).""" from fractions import Fraction class Poly: """A polynomial stored as {monomial: coefficient}; a monomial is a sorted tuple of (variable name, exponent) pairs.""" __slots__ = ('terms',) def __init__(self, terms=()): self.terms = {mono: coef for mono, coef in dict(terms).items() if coef} @classmethod def lift(cls, value): return value if isinstance(value, Poly) else cls({(): Fraction(value)}) def __add__(self, other): out = dict(self.terms) for mono, coef in Poly.lift(other).terms.items(): out[mono] = out.get(mono, 0) + coef return Poly(out) __radd__ = __add__ def __neg__(self): return Poly({mono: -coef for mono, coef in self.terms.items()}) def __sub__(self, other): return self + (-Poly.lift(other)) def __rsub__(self, other): return Poly.lift(other) - self def __mul__(self, other): out = {} for mono1, coef1 in self.terms.items(): for mono2, coef2 in Poly.lift(other).terms.items(): powers = dict(mono1) for name, exponent in mono2: powers[name] = powers.get(name, 0) + exponent mono = tuple(sorted(powers.items())) out[mono] = out.get(mono, 0) + coef1 * coef2 return Poly(out) __rmul__ = __mul__ def __pow__(self, exponent): out = Poly.lift(1) for _ in range(exponent): out = out * self return out def __truediv__(self, number): return self * (1 / Fraction(number)) def __eq__(self, other): return not (self - other).terms def __hash__(self): return hash(tuple(sorted(self.terms.items()))) def by_power(self, name): """The coefficients of the powers of one variable: {exponent: Poly in the other variables}.""" out = {} for mono, coef in self.terms.items(): exponent = dict(mono).get(name, 0) rest = tuple(pair for pair in mono if pair[0] != name) out[exponent] = out.get(exponent, Poly()) + Poly({rest: coef}) return {exponent: poly for exponent, poly in out.items() if poly.terms} def subs(self, name, value): """Replace one variable by a polynomial or a number.""" out = Poly() for exponent, coef in self.by_power(name).items(): out = out + coef * Poly.lift(value) ** exponent return out def with_square(self, name, square): """Reduce modulo name**2 = square, where square does not contain the variable.""" out = Poly() for exponent, coef in self.by_power(name).items(): out = out + coef * Poly.lift(square) ** (exponent // 2) * variables(name)[0] ** (exponent % 2) return out def number(self): """The value of a constant polynomial.""" if not self.terms: return Fraction(0) if set(self.terms) != {()}: raise ValueError('not a constant: %r' % (self.terms,)) return self.terms[()] def variables(*names): return [Poly({((name, 1),): Fraction(1)}) for name in names] def determinant3(rows): (a, b, c), (d, e, f), (g, h, i) = rows return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)