'Returns the coefficient from the term(s) containing ``x**n``. If ``n``
is zero then all terms independent of ``x`` will be returned.
When ``x`` is noncommutative, the coefficient to the left (default) or
right of ``x`` can be returned. The keyword \'right\' is ignored when
``x`` is commutative.
See Also
as_coefficient: separate the expression into a coefficient and factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.nth: like coeff_monomial but powers of monomial terms are used
Examples
>>> from sympy import symbols
>>> from sympy.abc import x, y, z
You can select terms that have an explicit negative in front of them:
>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y
You can select terms with no Rational coefficient:
>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0
You can select terms independent of x by making n=0; in this case
expr.as_independent(x)[0] is returned (and 0 will be returned instead
of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
from the following:
>>> (x + z*(x + x*y)).coeff(x)
1
If such factoring is desired, factor_terms can be used first:
>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols(\'n m o\', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n)
0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1'

def coeff(self, x, n=1, right=False):

    x = sympify(x)
    if (not isinstance(x, Basic)):
        return S.Zero
    n = as_int(n)
    if (not x):
        return S.Zero
    if (x == self):
        if (n == 1):
            return S.One
        return S.Zero
    if (x is S.One):
        co = [a for a in Add.make_args(self) if (a.as_coeff_Mul()[0] is S.One)]
        if (not co):
            return S.Zero
        return Add(*co)
    if (n == 0):
        if (x.is_Add and self.is_Add):
            c = self.coeff(x, right=right)
            if (not c):
                return S.Zero
            if (not right):
                return (self - Add(*[(a * x) for a in Add.make_args(c)]))
            return (self - Add(*[(x * a) for a in Add.make_args(c)]))
        return self.as_independent(x, as_Add=True)[0]
    x = (x ** n)
    def incommon(l1, l2):
        if ((not l1) or (not l2)):
            return []
        n = min(len(l1), len(l2))
        for i in range(n):
            if (l1[i] != l2[i]):
                return l1[:i]
        return l1[:]
    def find(l, sub, first=True):
        '    Find    where    list    sub    appears    in    list    l.    When    ``first``    is    True\n                                                the    first    occurance    from    the    left    is    returned,    else    the    last\n                                                occurance    is    returned.    Return    None    if    sub    is    not    in    l.\n\n                                                >>    l    =    range(5)*2\n                                                >>    find(l,    [2,    3])\n                                                2\n                                                >>    find(l,    [2,    3],    first=0)\n                                                7\n                                                >>    find(l,    [2,    4])\n                                                None\n\n                                                '
        if ((not sub) or (not l) or (len(sub) > len(l))):
            return None
        n = len(sub)
        if (not first):
            l.reverse()
            sub.reverse()
        for i in range(0, ((len(l) - n) + 1)):
            if all(((l[(i + j)] == sub[j]) for j in range(n))):
                break
        else:
            i = None
        if (not first):
            l.reverse()
            sub.reverse()
        if ((i is not None) and (not first)):
            i = (len(l) - (i + n))
        return i
    co = []
    args = Add.make_args(self)
    self_c = self.is_commutative
    x_c = x.is_commutative
    if (self_c and (not x_c)):
        return S.Zero
    if self_c:
        xargs = x.args_cnc(cset=True, warn=False)[0]
        for a in args:
            margs = a.args_cnc(cset=True, warn=False)[0]
            if (len(xargs) > len(margs)):
                continue
            resid = margs.difference(xargs)
            if ((len(resid) + len(xargs)) == len(margs)):
                co.append(Mul(*resid))
        if (co == []):
            return S.Zero
        elif co:
            return Add(*co)
    elif x_c:
        xargs = x.args_cnc(cset=True, warn=False)[0]
        for a in args:
            (margs, nc) = a.args_cnc(cset=True)
            if (len(xargs) > len(margs)):
                continue
            resid = margs.difference(xargs)
            if ((len(resid) + len(xargs)) == len(margs)):
                co.append(Mul(*(list(resid) + nc)))
        if (co == []):
            return S.Zero
        elif co:
            return Add(*co)
    else:
        (xargs, nx) = x.args_cnc(cset=True)
        for a in args:
            (margs, nc) = a.args_cnc(cset=True)
            if (len(xargs) > len(margs)):
                continue
            resid = margs.difference(xargs)
            if ((len(resid) + len(xargs)) == len(margs)):
                co.append((resid, nc))
        if (not co):
            return S.Zero
        if all(((n == co[0][1]) for (r, n) in co)):
            ii = find(co[0][1], nx, right)
            if (ii is not None):
                if (not right):
                    return Mul(Add(*[Mul(*r) for (r, c) in co]), Mul(*co[0][1][:ii]))
                else:
                    return Mul(*co[0][1][(ii + len(nx)):])
        beg = reduce(incommon, (n[1] for n in co))
        if beg:
            ii = find(beg, nx, right)
            if (ii is not None):
                if (not right):
                    gcdc = co[0][0]
                    for i in range(1, len(co)):
                        gcdc = gcdc.intersection(co[i][0])
                        if (not gcdc):
                            break
                    return Mul(*(list(gcdc) + beg[:ii]))
                else:
                    m = (ii + len(nx))
                    return Add(*[Mul(*(list(r) + n[m:])) for (r, n) in co])
        end = list(reversed(reduce(incommon, (list(reversed(n[1])) for n in co))))
        if end:
            ii = find(end, nx, right)
            if (ii is not None):
                if (not right):
                    return Add(*[Mul(*(list(r) + n[:((- len(end)) + ii)])) for (r, n) in co])
                else:
                    return Mul(*end[(ii + len(nx)):])
        hit = None
        for (i, (r, n)) in enumerate(co):
            ii = find(n, nx, right)
            if (ii is not None):
                if (not hit):
                    hit = (ii, r, n)
                else:
                    break
        else:
            if hit:
                (ii, r, n) = hit
                if (not right):
                    return Mul(*(list(r) + n[:ii]))
                else:
                    return Mul(*n[(ii + len(nx)):])
        return S.Zero
