6

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.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Ecir Hana
  • 10,864
  • 13
  • 67
  • 117
  • 1
    It's unfortunate that your example list is mirrored -- that makes it hard to tell which element is the coefficient of `x**0` and which is the coefficient for `x**2`. – mgilson Sep 04 '15 at 21:15
  • 1
    @mgilson It doesn't matter: take any ordering which suits you. What I try to say is that I could easily do `[::-1` if I needed to. – Ecir Hana Sep 04 '15 at 21:16

3 Answers3

9

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')
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • The only documentation I found for this is http://docs.sympy.org/0.7.1/modules/polys/reference.html which only mentions from_list() as a class method, then had to click on the source link to find out the class in question is Poly and still found no examples of this or other Poly class methods. Is there any better documentation for sympy.polys.polytools.Poly methods? –  Sep 04 '15 at 21:31
  • @TrisNefzger - I've had a look but not found any additional documentation for the method, unfortunately. I guess as SymPy is still a relatively young project the documentation still has some catching up to do... – Alex Riley Sep 04 '15 at 21:43
3

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
3

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')
Adrien
  • 469
  • 3
  • 11