Home > Software engineering >  How do I store factors of polynomials in a list in sympy?
How do I store factors of polynomials in a list in sympy?

Time:02-04

Suppose I have x^6-1 that I would like to factor, using .factor I get my irreducible factors, but I want those factors in a list. I tried using .factor_list() But it doesn't give me my desired result instead stores them in a tuple and there is always a 1 beside the factors. I want each factored polynomial in a list on its own, how can I do that if possible?

Like for example,

from sympy import Symbol, factor, Poly

x = Symbol('x')
p = x**6 - 1
factors = factor(p)
factors

that gives me these factors 4 irreducible factors, how do I store them in a list not as a tuple?

CodePudding user response:

I guess you could use as_terms() method

factors.as_terms()[1]

This would produce the following list:

[x - 1, x   1, x**2 - x   1, x**2   x   1]

CodePudding user response:

The output of factor_list is the leading coefficient and then a list of tuples of monic irreducible factors along with their multiplicity:

In [13]: factor_list(x**6 - 1)
Out[13]: 
⎛   ⎡                        ⎛ 2           ⎞  ⎛ 2           ⎞⎤⎞
⎝1, ⎣(x - 1, 1), (x   1, 1), ⎝x  - x   1, 1⎠, ⎝x    x   1, 1⎠⎦⎠

You can just extract the part of the return value that you want from the factor_list output:

In [12]: [f for f, m in factor_list(x**6 - 1)[1]]
Out[12]: 
⎡               2           2        ⎤
⎣x - 1, x   1, x  - x   1, x    x   1⎦
  • Related