Search code examples
listprintingjupytersympytypeset

Sympy: how to print a list of expressions all LaTeX typeset?


I have a list of polynomial expressions, (in my case obtained as the output of a Groebner basis computation), that I would like to view. I am using Jupyter, and I have started off with

import sympy as sy
sy.init_printing()

This causes an individual expression to be given nicely typeset. For a non-Groebner example:

sy.var('x')
fs = sy.factor_list(x**99-1)
fs2 = [x[0] for x in fs[1]]
fs2

The result is a nice list of LaTeX-typeset expressions. But how do I print these expressions one at a time; or rather; one per line? I've tried:

for f in fs2:
    sy.pprint(f)

but this produces ascii pretty printing, not LaTeX. In general the expressions I have tend to be long, and I really do want to look at them individually. I can of course do

fs2[0]
fs2[1]
fs2[2]

and so on, but this is tiresome, and hardly useful for a long list. Any ideas or advice? Thanks!


Solution

  • Jupyter (through IPython) has a convenience function called display which works well with SymPy:

    import sympy as sy
    sy.init_printing()
    sy.var('x')
    fs = sy.factor_list(x**99-1)
    fs2 = [x[0] for x in fs[1]]
    for f in fs2:
        display(f)
    

    Output:

    enter image description here

    You can also get the latex code for each of these polynomials by using the latex function:

    import sympy as sy
    from sympy.printing.latex import latex
    sy.init_printing()
    sy.var('x')
    fs = sy.factor_list(x**99-1)
    fs2 = [x[0] for x in fs[1]]
    for f in fs2:
        print(latex(f))
    

    Output:

    x - 1
    x^{2} + x + 1
    x^{6} + x^{3} + 1
    x^{10} + x^{9} + x^{8} + x^{7} + x^{6} + x^{5} + x^{4} + x^{3} + x^{2} + x + 1
    x^{20} - x^{19} + x^{17} - x^{16} + x^{14} - x^{13} + x^{11} - x^{10} + x^{9} - x^{7} + x^{6} - x^{4} + x^{3} - x + 1
    x^{60} - x^{57} + x^{51} - x^{48} + x^{42} - x^{39} + x^{33} - x^{30} + x^{27} - x^{21} + x^{18} - x^{12} + x^{9} - x^{3} + 1