Verbatim inside questions

The problem

The verbatim environment interferes with AMC LaTeX package, so that it is impossible to use it inside question or questionmult environments... As an example, the following code won't compile:

\begin{question}{program}
  What is the return value of the following R code?
  \begin{verbatim}
    sum(sapply(1:2^2,function(x) { x/2 }))
  \end{verbatim}
  \begin{choices}[o]
    \wrongchoice{2.5}
    \correctchoice{5}
    \wrongchoice{NaN}
  \end{choices}
\end{question}

Some solutions

Escaping

For very small texts, it is possible to escape all characters that have a special meaning for LaTeX. However, this can become quickly tedious...

\begin{question}{program}
  What is the return value of the following R code?
  \begin{center}
    \texttt{sum(sapply(1:2\textasciicircum 2,function(x) \{ x/2 \}))}
  \end{center}
  \begin{choices}[o]
    \wrongchoice{2.5}
    \correctchoice{5}
    \wrongchoice{NaN}
  \end{choices}
\end{question}

UseVerb

You can also record some one-line verbatims with the fancyvrb package (define your verbatim outside — before — \onecopy):

\SaveVerb{theRcode}'sum(sapply(1:2^2,function(x) { x/2 }))'

...

\begin{question}{program}
  What is the return value of the following R code?
  \begin{center}
    \UseVerb{theRcode}
  \end{center}
  \begin{choices}[o]
    \wrongchoice{2.5}
    \correctchoice{5}
    \wrongchoice{NaN}
  \end{choices}
\end{question}

Verbatim boxes

For larger verbatims, the verbatimbox package can help you:

\begin{myverbbox}{\Rcode}
sum(sapply(1:2^2,function(x) { x/2 }))
\end{myverbbox}

...

\begin{question}{program}
  What is the return value of the following R code?
  \begin{center}
    \Rcode
  \end{center}
  \begin{choices}[o]
    \wrongchoice{2.5}
    \correctchoice{5}
    \wrongchoice{NaN}
  \end{choices}
\end{question}

Separate file

Reading the verbatim from a separate file often helps. As an example, for a syntax highlighted python code stored in a file named prog.py in the project directory, you can use

  \lstset{language=Python}
  \lstinputlisting{prog.py}

from package listings, or

  \inputminted{python}{prog.py}

from package minted.