In this particular example, you can do:
sage: f1,f2 = f.operands()
sage: f1
(3*y + 2)^2
sage: f2
cos(x)
But it is not clear what do you expect with, for example exp(cos(x)*(3*y+2)^2)
? What do you mean by "separate" ? Is it only about the principal product ?
EDIT: according to your precisions: first you have to know whether the top-level operation is a product.
sage: from sage.symbolic.operators import mul_vararg
sage: f.operator() == mul_vararg
True
Then, you have to group the operands that contain only the variable x
, and those that do not contain the variable x
(if, again, i uinderstand correctly your comment): for this you have to inspect, for each operand
of the top-level product, if its variables
is equal to (x,)
of if it does not contain x
.
Putting everything together gives:
sage: def separate(f):
sage: from sage.symbolic.operators import mul_vararg
sage: if f.operator() == mul_vararg:
sage: xonly = []
sage: nox = []
sage: for term in f.operands():
sage: if term.variables() == (x,):
sage: xonly.append(term)
sage: elif x not in term.variables():
sage: nox.append(term)
sage: else:
sage: raise ValueError("There is a term that mixes x and other variables!")
sage: return (prod(xonly), prod(nox))
sage: else:
sage: raise ValueError("Not a product!")
Then, you can check on various examples:
sage: var('x,y,z')
(x, y, z)
sage: f=cos(x)*e^(cos(x))*(3*y+z)^2
sage: separate(f)
(cos(x)*e^cos(x), (3*y + z)^2)
sage: separate(x*log(y+z)*x^2*sin(x))
(x^3*sin(x), log(y + z))
sage: separate(x*log(y+x)*x^2)
ValueError: There is a term that mixes x and other variables!
sage: separate(x*log(y+x)*x^2)
ValueError: There is a term that mixes x and other variables!
sage: separate(log(x))
ValueError: Not a product!