Skip to content

Commit

Permalink
Do not compute parenthesization twice
Browse files Browse the repository at this point in the history
Previously both `PrettyPrinter._print_Mul` and `prettyForm.__mul__` tried to apply parenthesis, and the action of the former hid a typo in the latter.
  • Loading branch information
eric-wieser committed Oct 8, 2021
1 parent e359645 commit 9e509e6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 24 deletions.
22 changes: 4 additions & 18 deletions sympy/printing/pretty/pretty.py
Expand Up @@ -222,7 +222,7 @@ def _print_Relational(self, e):

l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
pform = prettyForm(*stringPict.next(l, op, r), binding=prettyForm.OPEN)
return pform

def _print_Not(self, e):
Expand Down Expand Up @@ -1767,23 +1767,9 @@ def _print_Mul(self, product):

from sympy import Integral, Piecewise, Product, Sum

# Convert to pretty forms. Add parens to Add instances if there
# is more than one term in the numer/denom
for i in range(0, len(a)):
if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and
isinstance(a[i], (Integral, Piecewise, Product, Sum))):
a[i] = prettyForm(*self._print(a[i]).parens())
elif a[i].is_Relational:
a[i] = prettyForm(*self._print(a[i]).parens())
else:
a[i] = self._print(a[i])

for i in range(0, len(b)):
if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and
isinstance(b[i], (Integral, Piecewise, Product, Sum))):
b[i] = prettyForm(*self._print(b[i]).parens())
else:
b[i] = self._print(b[i])
# Convert to pretty forms. Parentheses are added by `__mul__`.
a = [self._print(ai) for ai in a]
b = [self._print(bi) for bi in b]

# Construct a pretty form
if len(b) == 0:
Expand Down
15 changes: 9 additions & 6 deletions sympy/printing/pretty/stringpict.py
Expand Up @@ -441,18 +441,21 @@ def __mul__(self, *others):
}

if len(others) == 0:
return self # We aren't actually multiplying... So nothing to do here.
args = self
if args.binding > prettyForm.MUL:
arg = stringPict(*args.parens())
result = [args]
return self # We aren't actually multiplying... So nothing to do here.

# add parens on args that need them
arg = self
if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
arg = stringPict(*arg.parens())
result = [arg]
for arg in others:
if arg.picture[0] not in quantity.values():
result.append(xsym('*'))
#add parentheses for weak binders
if arg.binding > prettyForm.MUL:
if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
arg = stringPict(*arg.parens())
result.append(arg)

len_res = len(result)
for i in range(len_res):
if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'):
Expand Down

0 comments on commit 9e509e6

Please sign in to comment.