Factor out specific number using sympy

Viewed 398

I have an expression as follows:

from sympy import *
x = symbols('x')
ex = 2+2*x

I would like to factor out -2 from the expression. I have tried to factor using the .factor() method and this is what I got:

ex.factor()
>>> 2*(x + 1)

How can I explicitly set the factor I would like to use in sympy?

2 Answers

Here's how you can factor an expression by an arbitrary number. It can be a python int, or an Sympy number. Say we want to factor 2 + 2*x by 3/7:

def factor_by_num(expr,num):

    if not expr.is_Add:
        return None

    if isinstance(num,int):
        num_int = Integer(num)     
        divisor = Rational(1,num)

    elif hasattr(num,'is_Number'):
        num_int = num
        divisor= Rational(1,num)

    else:
        return None

    factored_args = map(lambda x: Mul(divisor,x),expr.args)
    return Mul(num_int,Add(*factored_args),evaluate=False)

x=Symbol('x')
ex = 2+2*x
ex_f = factor_by_num(ex,Rational(3,7))

This should do the trick

I am not aware of a way to do this. If you want to rewrite the expression by multiplying both args by -1, try a,b=factor(eq).args; Mul(-a, -b, evaluate=False).

Related