0

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?

rrryok
  • 55
  • 4
  • Welcome to Stack Overflow. We can help you more quickly if you show some code to go along with your English and mathematical notation. – Code-Apprentice Nov 19 '21 at 16:10
  • Does this answer your question? [How to extract all coefficients in sympy](https://stackoverflow.com/questions/22955888/how-to-extract-all-coefficients-in-sympy) – JNevill Nov 19 '21 at 16:29

2 Answers2

1

SymPy can give you those coefficients, but there are several nuances to the question:

  1. how can you get SymPy to recognize this expression?
    >>> 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
  1. the simplest way to separate a term from its coefficient is 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)
  1. the problem with 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?

smichr
  • 16,948
  • 2
  • 27
  • 34
0
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.

Ruggero
  • 427
  • 2
  • 10
  • i have an error 'Add' object has no attribute 'coeffs'. Maybe because i have an equation not polynom – rrryok Nov 19 '21 at 16:36