# Pretty print factorizations as fractions

Hi all,

If I have an object whose factorization makes sense when expressed as a fraction, how do I get Sage to pretty print its factorization as a fraction instead of a product of factors? For example,

sage: R.<x> = PolynomialRing(QQ)
sage: f = (x - 1)^2 / (x + 1)
sage: f
(x^2 - 2*x + 1)/(x + 1)
sage: f.factor()
(x + 1)^-1 * (x - 1)^2


but ideally I would like some way to pretty print f as (x - 1)^2/(x + 1).

Thanks,

Henry

edit retag close merge delete

Sort by » oldest newest most voted Convert to the symbolic ring ?

sage: x = polygen(QQ, 'x')
sage: unicode_art((x**3+4)/(x**7-66))
(x^3 + 4)/(x^7 - 66)
sage: unicode_art(SR((x**3+4)/(x**7-66)))
3
x  + 4
───────
7
x  - 66

sage: unicode_art(SR(factor((x**3+4)/(x**4-1))))
3
x  + 4
────────────────────────
⎛ 2    ⎞
(x - 1)⋅(x + 1)⋅⎝x  + 1⎠

more

One way to do that is to factor the numerator and then the denominator:

sage: print('({})/({})'.format(f.numerator().factor(), f.denominator().factor()))
((x - 1)^2)/(x + 1)


One could turn this into a function with a special case for no denominator:

def pretty_print_factor(f):
d = f.denominator()
if d == 1:
print(f.factor())
else:
n = f.numerator().factor()
print('({})/({})'.format(n, d.factor()))


Using this function, we get:

sage: pretty_print_factor(f)
((x - 1)^2)/(x + 1)


The function could be improved to leave out parenthesis when not needed.

more