coeffs() can be used like this
expr = 3/x + 4*x
a = Poly(expr)
a.coeffs()
# [4, 3]
If expr consists of either all +ve or all -ve
I don't know if it is intentional for -ve powers but all_coeff() can be
used like
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]
- But it does not work when the expression is a combination of +ve and -ve
powers.
example:
expr = 3/x + 4*x
a = Poly(expr)
a.all_coeffs()
# error
If you know the range of powers you can make a dictionary using this.
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}
I have faced this exact problem few days back where I wanted an output as a
dictionary where keys are powers and values are coefficient, I wrote a
function for this:
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/x
coeff_exp(expr)
# {1: 1, -1: 2}
expr = 2*x**3 + x
coeff_exp(expr)
# {1: 1, 3: 2}
expr = -3/x**3 + 2/x
coeff_exp(expr)
# {-3: -3, -1: 2}
On Friday, 20 March 2020 16:30:56 UTC+5:30, Jisoo Song wrote:
>
> I know there is 'coeff' method, which gives the coefficient of specific
> power of variable: e.g. (3/x + 4*x).coeff(x, -1) giving 3.
>
> 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.
>
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/4c9069ab-6c34-4c36-89b9-d4e39ab9ea17%40googlegroups.com.