LaTeX 包minted提供了非常广泛的语法突出显示(基于 Pygments)并允许双向交叉引用。您可以从代码部分(铸造部分)中转义到 LaTeX,并且可以在正文中引用代码行。最重要的是,它提供了一个列表环境,以便您可以生成“列表列表”(如表格列表)并允许引用整个列表。请参阅下面的 LaTeX MWE 及其与 LuaLaTeX 的输出(不要判断代码:-))。
另一种选择是使用来自同一作者/维护者的PythonTeX,它允许在编译 LaTeX 源代码的同时运行计算,因此论文和代码结果总是一起生成,因此总是连贯的。在此处查看PythonTeX 库。
\documentclass[a4paper,notitlepage,11pt]{article}
\usepackage{amsmath}
\usepackage{cases}
\usepackage{minted}
\begin{document}
The mathematical definition of the Fibonacci
series is given in~Equations~(\ref{eq:fibdef:init1}--\ref{eq:fibdef:rule})
It can be implemented using either a recursive or iterative algorithm
in Python.
\begin{numcases}{f(n)=}
\label{eq:fibdef}
0 & n = 0 \label{eq:fibdef:init1}\\
1 & n = 1 \label{eq:fibdef:init2}\\
f(n-1) + f(n-2) & \text{otherwise} \label{eq:fibdef:rule}
\end{numcases}
The algorithms below are an implementation of both variants.
Listing~\ref{alg:fib_recursive} shows the recursive variant (see
line~\ref{alg:fibo_rec:line_rec} in listing~\ref{alg:fib_recursive}) while
listing~\ref{alg:fib_iterative} shows the iterative variant. Both can be
optimized, of course.
\begin{listing}[ht]
\begin{minted}[linenos, escapeinside=||]{python}
def fibo_rec(N):
if N == 0:
result = 1 |[Comment: See case (\ref{eq:fibdef:init1})]|
elif N == 1:
result = 1 |[Comment: See case (\ref{eq:fibdef:init2})]|
else:
result = fibo_rec(N-1) + fibo_rec(N-2) |\label{alg:fibo_rec:line_rec}[Comment: See case (\ref{eq:fibdef:rule})]|
return result
\end{minted}
\caption{Fibonacci recursive}
\label{alg:fib_recursive}
\end{listing}
\begin{listing}[ht]
\begin{minted}[linenos, escapeinside=||]{python}
def fibo_iter(N):
if N == 0:
fib_N = 1
elif N == 1:
fib_N = 1
else:
fib_Nmin2 = 1
fib_Nmin1 = 1
for i in range(2,N+1):
fib_N = fib_Nmin2 + fib_Nmin1
fib_Nmin2 = fib_Nmin1
fib_Nmin1 = fib_N
return fib_N
\end{minted}
\caption{Fibonacci iterative}
\label{alg:fib_iterative}
\end{listing}
\end{document}