I have a polynomial with multiple variables, for example:
2c1^2*c2*x^3+c2*x
represented in python by
Poly(2*c1**2*c2*x**3 + c2*x, c1, c2, x, domain='ZZ')
I would like to iterate over the monomials, and each time I find "c1^2", divide this monomial by c1*x. For the example above, the result should be:
2c1*c2*x^2+c2*x
represented in python by
Poly(2*c1*c2*x**2 + c2*x, c1, c2, x, domain='ZZ')
how can this be done? Specifically, how do I manipulate each monomial separately? I expect to have polynomials with dozens of monomials. Is sympy.Poly the appropriate package to use in this case?
I'll show you how I would do it.
from sympy import *
c1, c2, x = symbols("c1, c2, x")
poly = Poly(2*c1**2*c2*x**3 + c2*x, c1, c2, x, domain='ZZ')
# convert the Poly to an expression
expr = poly.as_expr()
# expr is of type Add (an addition). Let's extract the addends
monomials = expr.args
# perform the manipulation
mod_expr = Add(*[m / (c1 * x) if m.has(c1**2) else m for m in monomials])
# create a new Poly: use the new expression and the original symbols/domain
new_poly = Poly(mod_expr, poly.args[1:], domain=poly.domain)
print(new_poly)
# out: Poly(2*c1*c2*x**2 + c2*x, c1, c2, x, domain='ZZ')
Regarding your question:
Is sympy.Poly the appropriate package to use in this case?
That's up to you to decide. As you have seen from this simple example, I operated directly on a symbolic expression. So, if you input your polynomials as symbolic expressions instead of Poly
, you might save yourself some typing.