+ @classmethod
+ def fromsympy(cls, expr):
+ import sympy
+ coefficients = {}
+ constant = 0
+ for symbol, coefficient in expr.as_coefficients_dict().items():
+ coefficient = Fraction(coefficient.p, coefficient.q)
+ if symbol == sympy.S.One:
+ constant = coefficient
+ elif isinstance(symbol, sympy.Symbol):
+ symbol = symbol.name
+ coefficients[symbol] = coefficient
+ else:
+ raise ValueError('non-linear expression: {!r}'.format(expr))
+ return cls(coefficients, constant)
+
+ def tosympy(self):
+ import sympy
+ expr = 0
+ for symbol, coefficient in self.coefficients():
+ term = coefficient * sympy.Symbol(symbol)
+ expr += term
+ expr += self.constant
+ return expr
+