Andrew Mir
Andrew Mir

Reputation: 125

How in sympy Disable unnecessary parenthesis?

Tell me please, How to forbid to open brackets? For example, 8 * (x + 1) It should be that way, not 8 * x + 8 Using evaluate = False doesn't help

Upvotes: 2

Views: 773

Answers (3)

smichr
smichr

Reputation: 19115

The global evaluate flag will allow you to do this in the most natural manner:

>>> with evaluate(False):
...  8*(x+1)
...
8*(x + 1)

Otherwise, Mul(8, x + 1, evaluate=False) is a lower level way to do this. And conversion from a string (already in that form) is possible as

>>> S('8*(x+1)',evaluate=False)
8*(x + 1)

Upvotes: 2

JohanC
JohanC

Reputation: 80439

In general, SymPy will convert the expression to its internal format, which includes some minimal simplifications. For example, sqrt is represented internally as Pow(x,1/2). Also, some reordering of terms may happen.

In your specific case, you could try:

from sympy import factor
from sympy.abc import x, y

y = x + 1
g = 8 * y
g = factor(g)
print(g)  # "8 * (x + 1)"

But, if for example you have g = y * y, SymPy will either represent it as a second power ((x + 1)**2), or expand it to x**2 + 2*x + 1.

PS: See also this answer by SymPy's maintainer for some possible workarounds. (It might complicate things later when you would like to evaluate or simplify this expression in other calculations.)

Upvotes: 1

Emil Vatai
Emil Vatai

Reputation: 2531

How about sympy.collect_const(sympy.S("8 * (x + 1)"), 8)?

In general you might be interested in some of these expression manipulations: https://docs.sympy.org/0.7.1/modules/simplify/simplify.html

Upvotes: 0

Related Questions