Mathew
Mathew

Reputation: 1430

get coefficient of a monomial in a sympy expression

I have a sympy expression like so:

exp_str = '3 * x**2*y  +  4*a**2 * x*y  +  9*b * x'
my_expr = sp.parsing.sympy_parser.parse_expr(exp_str)

and I want to get the coefficient of x*y, which should be 4*a**2.

Is there a function that I can pass my_expr to along with a list of variables I want my polynomial to be over? For example, I would need to pass this function x and y so that it knows x and y are variables and that a and b are coefficients.

If there is no such function, and recommendations on how to write code to do this would be appreciated. Thanks

Upvotes: 0

Views: 369

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

There is a coeff method of sympy expressions:

In [28]: x, y, a, b = symbols('x, y, a, b')

In [29]: expr = 3 * x**2*y  +  4*a**2 * x*y  +  9*b * x

In [30]: expr.coeff(x*y)
Out[30]: 
   2
4⋅a

https://docs.sympy.org/latest/modules/core.html?highlight=coeff#sympy.core.expr.Expr.coeff

You might find it useful though to work with expressions as structured polynomials e.g.:

In [31]: p = Poly(expr, [x, y])

In [32]: p
Out[32]: Poly(3*x**2*y + 4*a**2*x*y + 9*b*x, x, y, domain='ZZ[a,b]')

In [33]: p.coeff_monomial(x**2 * y)
Out[33]: 3

In [34]: p.coeff_monomial(x * y)
Out[34]: 
   2
4⋅a 

https://docs.sympy.org/latest/modules/polys/basics.html

Upvotes: 1

Related Questions