undefinedfix
Sign in

How to get the second factor in Python's sympy factorization?

user615952 edited in Thu, 23 Jun 2022
import sympy
x=sympy.symbols('x')
r=sympy.factor(x**7-1)
print(sympy.factor(x**7-1))
(x - 1)*(x**6 + x**5 + x**4 + x**3 + x**2 + x + 1)

How can I get the second expression (x * * 6 + X * * 5 + X * * 4 + X * * 3 + X * * 2 + X + 1) and then operate it? thank you

1 Replies
user282
commented on Fri, 24 Jun 2022

Using factor_ List, you can do this:

import sympy
from sympy import factor_list

x = sympy.symbols('x')
r = sympy.factor(x**7 - 1)
print(r)

f_list = factor_list(r)
print(f_list)
# (1, [(x - 1, 1), (x**6 + x**5 + x**4 + x**3 + x**2 + x + 1, 1)])

s = f_list[1][1][0]
print(s)
# x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
print(type(s))
# <class 'sympy.core.add.Add'>
# 假设让 x = 1 执行结果:
print(s.evalf(subs={x:1}))    # 7.00000000000000

reference resources : docs . sympy . org / simplification # factor

Or, you can do this (the expression removes (x-1)):

x = sympy.symbols('x')
r = sympy.symbols(x**7 - 1)
s = r / (x - 1)
print(s)
# x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
lock This question has been locked and the reply function has been disabled.