Then, is there any method to give every coeffecient of powers of x? For example, {-1:3, 1:4} where keys are powers and values are coefficient.
expr = 3/x + 4*x
a = Poly(expr)
a.coeffs()
# [4, 3]expr = 3*x**3 + 2*x
a = Poly(expr)
a.all_coeffs()
# [3, 0, 2, 0]
expr = 4/x**3 + 3/x
a = Poly(expr)
a.all_coeffs()
# [4, 0, 3, 0]expr = 3/x + 4*x
a = Poly(expr)
a.all_coeffs()
# error
expr = 3/x + 4*x
dict = {p: expr.collect(x).coeff(x,p) for p in range(low_r,high_r) if expr.collect(x).coeff(x,p)!=0 }
# {1: 4, -1: 3}
def coeff_exp(expr): a = Poly(expr) x = list(expr.free_symbols)[0] values = a.rep.rep solution, length = dict(), len(values) positive, negative, len_p, len_n = False, False, 0, 0 if type(values[0]) == list: #combination of -ve and +ve powers positive, negative = values[0], values[1] len_p, len_n = len(positive), len(negative) elif expr.coeff(x,length - 1) == values[0]: #all +ve powers positive = values len_p = length - 1 else: #all -ve powers negative = values len_n = length
if positive: solution.update({len_p - i: val for i,val in enumerate(positive) if val!=0}) if negative: solution.update({-len_n + i + 1: val for i,val in enumerate(negative) if val!=0})
return solution
x = Symbol("x")
expr = x + 2/xcoeff_exp(expr)
# {1: 1, -1: 2}
expr = 2*x**3 + xcoeff_exp(expr)
# {1: 1, 3: 2}
expr = -3/x**3 + 2/xcoeff_exp(expr)# {-3: -3, -1: 2} >>> y = 2*x**3 + a*x**2 + b>>> d = dict(i.as_independent(x)[::-1] for i in Add.make_args(y)); d
{1: b, x**3: 2, x**2: a}>>> def codict(expr, *x):
... collected = Poly(expr, *x).as_expr()
... return dict(i.as_independent(*x)[::-1] for i in Add.make_args(collected))
...
>>> x, a = symbols("x, a")
>>> y = 3 + x + x**2 + a*x*2
>>> codict(y, x)
{1: 3, x**2: 1, x: 2*a + 1}
>>> codict(y+b*z,x,z)
{1: 3, x**2: 1, z: b, x: 2*a + 1}