Search code examples
pythonsympysymbolic-mathpolynomials

Make sympy write out an expression in polynomial form


Currently, I have an expression of the form

(a+x^2) / b + x /c + xd + k

How can I make sympy to write it out in a polynomial form for x as

x^2 (.)+ x() + (.) 

And then I want to be able to access the coefficients of that polynomial, i.e. the terms in the brackets.


Solution

  • You can use the Poly class and the all_coeffs method. The reference is accessible here: https://docs.sympy.org/latest/modules/polys/reference.html

    This is what it would give with your example, assuming all symbols have been declared:

    >>> pol = sp.Poly(((a+x**2) / b + x /c + x*d + k), x); pol
    Poly(1/b*x**2 + (c*d + 1)/c*x + (a + b*k)/b, x, domain='ZZ(a,b,c,d,k)')
    >>> pol.all_coeffs()
    [1/b, (c*d + 1)/c, (a + b*k)/b]
    

    After that you can access each coefficient with its position.