# collect variables buried in an expression

Suppose we have

var('Pmean,alpha,M,Nb,D,H,c');
sol3= [M == 1/4*(2*D*Nb*Pmean - (D*H*alpha + D*H)*c)/((alpha + 1)*c)]


How would you collect the coefficients of D*H in the second term?

Specifically, once the collection is done, how could the factored version of the expression be returned?

I know from using other computer algebra systems that it can be taken all the way to this:

M==1/4*D*(-H+(2*Nb*Pmean)/((1+alpha)*c))

edit retag close merge delete

Sort by » oldest newest most voted

sage: expr = sol3.rhs()
sage: expr.coefficient(D*H)
-1/4


let me mention that wild cards could also be useful in this type of task:

sage: var('DH'); w0 = SR.wild();
sage: expr.subs({D*H*w0 : DH*w0}).coefficient(DH)
-1/4


Edit: there is the following trick of adding/removing the term of interest which works here:

sage: DHterm = expr.coefficient(D*H)*D*H
sage: ((expr-DHterm).factor() + DHterm).collect(D)
-1/4*D*(H - 2*Nb*Pmean/((alpha + 1)*c))


... but it would be nice to know if there is a more "direct" (=one command) method!

more

I gave an upvote because you showed me something new. I am also updating my question to clarify it.

It sometimes helps to expand and factor:

sage: s
1/4*(2*D*Nb*Pmean - (D*H*alpha + D*H)*c)/((alpha + 1)*c)
sage: s.expand()
-1/4*D*H*alpha/(alpha + 1) - 1/4*D*H/(alpha + 1) + 1/2*D*Nb*Pmean/((alpha + 1)*c)
sage: _.factor()
-1/4*(H*alpha*c - 2*Nb*Pmean + H*c)*D/((alpha + 1)*c)
sage: _.partial_fraction()
1/4*(2*Nb*Pmean - (H*alpha + H)*c)*D/((alpha + 1)*c)

more