Reputation: 61
For a project I am working on I have to select a specific term from an arbitrary SymPy expression. For this I am using .args
which works fine if the expression consists of multiple distinct terms, but returns the individual coefficients in the term if only a single term is present. See the following example:
import sympy as sym
x, c0, c1 = sym.symbols('x c0 c1')
f0 = c0*x
f1 = c1*x**2
f2 = c0*x + c1*x**2
print(f0.args) # Output: (c0, x) Desired: (c0*x)
print(f1.args) # Output: (c1, x**2) Desired: (c1*x**2)
print(f2.args) # Output: (c0*x, c1*x**2)
This method works as I would want it to for f2
, where it returns (c0*x, c1*x**2)
. For f0
and f1
however it returns the coefficients c0, c1
and x
separately. How would I go achieving the desired output where for the single term expressions the coefficients and x
are also returned as a multiplicative expression?
Note that ideally I would want this method to work for any form of expression, with arbitrary dependencies on x
and an arbitrary amount of coefficients.
Upvotes: 1
Views: 754
Reputation: 61
Credit goes to Oscar Benjamin. Since I can't accept their comment as the answer I am reposting it here while also providing a concrete example.
"You can use Add.make_args(f0)
"
This would then look like this:
import sympy as sym
x, c0, c1 = sym.symbols('x c0 c1')
f0 = c0*x
f1 = c1*x**2
f2 = c0*x + c1*x**2
print(sym.Add.make_args(f0))
print(sym.Add.make_args(f1))
print(sym.Add.make_args(f2))
Which would return:
(c0*x,)
(c1*x**2,)
(c0*x, c1*x**2)
Upvotes: 2
Reputation: 11504
You need to use poly
to state the fact that you have polynomials:
import sympy as sym
from sympy import symbols, Poly
x, c0, c1 = sym.symbols('x c0 c1')
f0 = sym.poly(c0*x)
f1 = sym.poly(c1*x**2)
f2 = c0*x + c1*x**2
print(f0.args) # Output: (c0, x) Desired: (c0*x)
print(f1.args) # Output: (c1, x**2) Desired: (c1*x**2)
print(f2.args) # Output: (c0*x, c1*x**2)
returns
(c0*x, x, c0)
(c1*x**2, x, c1)
(c0*x, c1*x**2)
to get the monimials, simply use
f0.args[0]
which gives
c0*x
Upvotes: 0