'Determine individual terms of SymPy expression
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge de Gosson de Varennes |
