I have a very long sympy equation that look like this:
a^2 + 2ab + 2a^2*b + 3b^2
and i want to get this list:
[1,2,2,3]
How can i do this?
I have a very long sympy equation that look like this:
a^2 + 2ab + 2a^2*b + 3b^2
and i want to get this list:
[1,2,2,3]
How can i do this?
SymPy can give you those coefficients, but there are several nuances to the question:
>>> from sympy import parse_expr
>>> eq = parse_expr('a^2 + 2ab + 2a^2*b + 3b^2', transformations='all')
>>> eq
2*a**2*b + a**2 + 2*a*b + 3*b**2
as_coeff_Mul
and the way to get the terms of a sum is with .args
so >>> co, trm = zip(*[i.as_coeff_Mul() for i in eq.args])
>>> co
(1, 3, 2, 2)
>>> trm
(a**2, b**2, a*b, a**2*b)
Poly.coeffs()
is that it is not transparent for which monomial the coefficient is given and Poly methods are lower-level in terms of information. But for completeness >>> p = Poly(eq)
>>> p.gens
(a, b)
>>> p.terms()
[((2, 1), 2), ((2, 0), 1), ((1, 1), 2), ((0, 2), 3)]
Do you see the relationship between gens, the monomial exponents and the coefficients?
import sympy as sy
a,b = sy.symbols('a,b')
your_poly = sy.poly(a**2 + 2*a*b + 2*a**2*b + 3*b**2)
print(your_poly.coeffs())
The output will be:
[2, 1, 2, 3]
since the function sorts from the highest to the lowest polynomial degree.