On Wed, Nov 28, 2012 at 9:18 AM, ThanhVu Nguyen
<nguyenthanh...@gmail.com> wrote:
>
> I am wondering how to obtain the coefs and terms of a given expression in
> sympy.  For example, given  the expression  a**2+b+5*c+2,  I want to get the
> coefs [1,1,5,2] and the terms [a^2,b,c,1].

As a related question, recently I needed to extract the coefficient in
a polynomial of t of a particular power of t:

t**12*Ra(6)**2 + 2*t**11*Ra(5)*Ra(6) + 2*t**10*Ra(4)*Ra(6) +
t**10*Ra(5)**2 + 2*t**9*Ra(3)*Ra(6) + 2*t**9*Ra(4)*Ra(5) +
2*t**8*Ra(2)*Ra(6) + 2*t**8*Ra(3)*Ra(5) + t**8*Ra(4)**2 +
2*t**7*Ra(1)*Ra(6) + 2*t**7*Ra(2)*Ra(5) + 2*t**7*Ra(3)*Ra(4) +
2*t**6*Ra(0)*Ra(6) + 2*t**6*Ra(1)*Ra(5) + 2*t**6*Ra(2)*Ra(4) +
t**6*Ra(3)**2 + 2*t**5*Ra(0)*Ra(5) + 2*t**5*Ra(1)*Ra(4) +
2*t**5*Ra(2)*Ra(3) + 2*t**4*Ra(0)*Ra(4) + 2*t**4*Ra(1)*Ra(3) +
t**4*Ra(2)**2 + 2*t**3*Ra(0)*Ra(3) + 2*t**3*Ra(1)*Ra(2) +
2*t**2*Ra(0)*Ra(2) + t**2*Ra(1)**2 + 2*t*Ra(0)*Ra(1) + Ra(0)**2

Given the above polynomial [which is just the expansion of (t**6*Ra(6)
+ t**5*Ra(5) + t**4*Ra(4) + t**3*Ra(3) + t**2*Ra(2) + t*Ra(1) +
Ra(0))**2 given some function Ra()] I needed to query it for the
coefficients of t**d for a particular d. From the answer by Aaron
Meurer, it seems I can do:

Poly(above_polynomial,t).allcoeffs()[-d-1]

but it is not so elegant, and it also throws an IndexError if I query
for some d greater than the degree of the polynomial whereas ideally a
function something like: Poly.coeff_for_degree(d) would return 0 in
such cases. Is such a function coeff_for_degree available? The input
and output for such a function on the above (squared) polynomial would
be what I got by doing:

>>> for (p,v) in enumerate(reversed(Poly(mysum,t).all_coeffs())): print(p,v)
0 Ra(0)**2
1 2*Ra(0)*Ra(1)
2 2*Ra(0)*Ra(2) + Ra(1)**2
3 2*Ra(0)*Ra(3) + 2*Ra(1)*Ra(2)
4 2*Ra(0)*Ra(4) + 2*Ra(1)*Ra(3) + Ra(2)**2
5 2*Ra(0)*Ra(5) + 2*Ra(1)*Ra(4) + 2*Ra(2)*Ra(3)
6 2*Ra(0)*Ra(6) + 2*Ra(1)*Ra(5) + 2*Ra(2)*Ra(4) + Ra(3)**2
7 2*Ra(1)*Ra(6) + 2*Ra(2)*Ra(5) + 2*Ra(3)*Ra(4)
8 2*Ra(2)*Ra(6) + 2*Ra(3)*Ra(5) + Ra(4)**2
9 2*Ra(3)*Ra(6) + 2*Ra(4)*Ra(5)
10 2*Ra(4)*Ra(6) + Ra(5)**2
11 2*Ra(5)*Ra(6)
12 Ra(6)**2

Thanks!

-- 
Shriramana Sharma

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To post to this group, send email to sympy@googlegroups.com.
To unsubscribe from this group, send email to 
sympy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sympy?hl=en.

Reply via email to