How do I create a polynomial out of a list of coefficients in SymPy?
For example, given a list [1, -2, 1]
I would like to get Poly(x**2 - 2*x + 1)
. I tried looking at the docs but could not find anything close to it.
How do I create a polynomial out of a list of coefficients in SymPy?
For example, given a list [1, -2, 1]
I would like to get Poly(x**2 - 2*x + 1)
. I tried looking at the docs but could not find anything close to it.
You could use Poly.from_list
to construct the polynomial:
>>> x = sympy.Symbol('x')
>>> sympy.Poly.from_list([1, -2, 1], gens=x)
Poly(x**2 - 2*x + 1, x, domain='ZZ')
It looks to me like you would do something like:
from sympy.abc import x
from sympy import poly
lst = [1, -2, 1]
poly(sum(coef*x**i for i, coef in enumerate(reversed(lst))))
Of course, you don't depending on which coefficient maps to x**0
, you might not need the reversed
in the above.
This simpler alternative works for me (Sympy 0.7.6.1):
>>> from sympy import Symbol, Poly
>>> x = Symbol('x')
>>> Poly([1,2,3], x)
Poly(x**2 + 2*x + 3, x, domain='ZZ')
© 2022 - 2024 — McMap. All rights reserved.
x**0
and which is the coefficient forx**2
. – Dennadennard[::-1
if I needed to. – Casein