Skip to content
Advertisement

Extract coefficients and corresponding monomials from a given polynomial in SymPy

Given a symbolic multivariate polynomial P, I need to extract both its coefficients and corresponding monomials as lists:

JavaScript

such that P is the dot product of coefficients and monomials, e.g., if P(x,y) = ax**2 + bxy + cy**2 then we should get coeffs = [a, b, c] and monoms = [x**2, x*y, y**2].

Getting the coefficients is easy since the function is built in coeffs = P.coeffs(). However, I’m having trouble getting the monomials. Here the build in function returns a list of exponents, e.g., in the example above we would get P.monoms() = [(2,0),(1,1),(0,2)].

Obviously the idea would be, provided a list of the variables var=[x,y], to do something like

JavaScript

However the polynomial class doesn’t seem to offer a function that returns a list of variables. All I could find were the methods free_symbols and free_symbols_in_domain which return the sets {a, b, c, x, y} and {a, b, c}. So by taking their difference one could get the set {x, y}.

However then we are faced with the issue that the sets are unordered, hence converting it into a list might mess up the order in different ways depending on the number of variables.

I am kind of at a loss here. Any tips?

Advertisement

Answer

The property gens (short for generators) holds a tuple of symbols or other suitable objects that the polynomial is defined over.

JavaScript

So,

JavaScript

returns [x**3, x**2, x*y, y**3, y**2].

Note also that the generators can be types other than symbols, for example:

JavaScript

which prints:

JavaScript

where:

  • type(poly.gens[0]) is <class 'sympy.core.symbol.Symbol'>, and
  • type(poly.gens[1]) is <class 'sympy.core.power.Pow'>.

A relevant method is sympy.polys.polytools.Poly.as_dict, which returns a dict with keys that are monomials, and values that are the corresponding coefficients.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement