[Tex/LaTex] Formatting columns with multicols and lstlisting

formattingtables

I want to get the code displayed in the picture below to come after the title I have for it. I know I have previously asked this question but it was detailing with enumerated items. Can I get some help making this look better?

enter image description here

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage[mathscr]{euscript}
\usepackage{enumerate}
\usepackage{amsfonts}
\usepackage{multicol}
\usepackage{listings}

\begin{document}

\parindent0pt

\newtheorem{prob}{Problem}

\setcounter{prob}{3}
\begin{prob}
Write a python function $sumsq$ that takes as input a positive integer $n$ and returns the sum of the squares of the integers in the list $1, \dots, n$. Print  out the values of $sumsq(n)$ for $n=1,\dots, 20$
\end{prob}

\begin{multicols}{2}
\textbf{Code for Problem 4:} 
\begin{lstlisting}
def sumsq(n):
    total = 0
    for i in range(1,n+1):
        total = total+(i**2)
    return(total)
\end{lstlisting}

\columnbreak

\textbf{Printout of Code for Problem 4:}
\begin{lstlisting}
>>> for i in range(1,20): sumsq(i)

1
5
14
30
55
91
140
204
285
385
506
650
819
1015
1240
1496
1785
2109
2470
\end{lstlisting}
\end{multicols}

\end{document}

Best Answer

I suggest you use minipages instead of a multicol environment.

Sample output

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{document}

\parindent0pt

\newtheorem{prob}{Problem}

\setcounter{prob}{3}
\begin{prob}
Write a python function $sumsq$ that takes as input a positive integer $n$ and returns the sum of the squares of the integers in the list $1, \dots, n$. Print  out the values of $sumsq(n)$ for $n=1,\dots, 20$
\end{prob}

\begin{center}
  \begin{minipage}[t]{0.45\linewidth}
    \textbf{Code for Problem 4:}
\begin{lstlisting}
def sumsq(n):
    total = 0
    for i in range(1,n+1):
        total = total+(i**2)
    return(total)
\end{lstlisting}
  \end{minipage}
  \qquad
  \begin{minipage}[t]{0.47\linewidth}
    \textbf{Printout of Code for Problem 4:}
\begin{lstlisting}
>>> for i in range(1,20): sumsq(i)

1
5
14
30
55
91
140
204
285
385
506
650
819
1015
1240
1496
1785
2109
2470
\end{lstlisting}
  \end{minipage}
\end{center}

\end{document}

You should adjust the widths as appropriate.

Related Question