LaTeX显示程序代码块
默认可以使用verbatim环境展示代码, 通常使用listings
包中的lstlisting
环境来显示。
导言区设置样式
\usepackage{listings} %导入包
\definecolor{codebrown}{rgb}{0.8,0.44,0.2}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codebrown},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
% numbersep=5pt,
% numbers=none,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=0.1\textwidth,
xrightmargin=0.1\textwidth
}
\lstset{style=mystyle}
样例代码
\begin{lstlisting}[language=Python, caption=Python example]
import numpy as np
def incmatrix(genl1,genl2):
m = len(genl1)
n = len(genl2)
M = None #to become the incidence matrix
VT = np.zeros((n*m,1), int) #dummy variable
#compute the bitwise xor matrix
M1 = bitxormatrix(genl1)
M2 = np.triu(bitxormatrix(genl2),1)
for i in range(m-1):
for j in range(i+1, m):
[r,c] = np.where(M2 == M1[i,j])
for k in range(len(r)):
VT[(i)*n + r[k]] = 1;
VT[(i)*n + c[k]] = 1;
VT[(j)*n + r[k]] = 1;
VT[(j)*n + c[k]] = 1;
if M is None:
M = np.copy(VT)
else:
M = np.concatenate((M, VT), 1)
VT = np.zeros((n*m,1), int)
return M
\end{lstlisting}
参考:https://www.overleaf.com/learn/latex/Code_listing