factor an expression in python

One way to factor an expression in Python is to use the sympy library. Here's an example:

main.py
from sympy import Symbol, factor

x = Symbol('x')
expr = x**2 + 2*x + 1
factored_expr = factor(expr)

print(factored_expr)
123 chars
8 lines

Output:

main.py
(x + 1)**2
11 chars
2 lines

In this example, we first define the symbol x using the Symbol function. Then, we define our expression as x**2 + 2*x + 1. Finally, we use the factor function to factor our expression and store the result in factored_expr.

The output shows that the expression (x + 1)**2 is the factored form of x**2 + 2*x + 1.

gistlibby LogSnag