我试图提供如下一些代码:
\documentclass[11pt]{beamer}
\usepackage{tcolorbox}
\tcbuselibrary{listings,skins}
\lstdefinestyle{compactstyle}{
numbers=left,
numberstyle=\small,
numbersep=8pt,
language=Python,
basicstyle=\tiny
}
\newtcblisting{compactlisting}[2][]{
arc=0pt, outer arc=0pt,
listing only,
listing style=compactstyle,
title=#2,
#1
}
\usepackage{listings,newtxtt}
\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}
\begin{document}
\begin{frame}[fragile]
\frametitle{Title}
\begin{compactlisting}[hbox]{}
def peak_recursive(A):
n = len(A)
if n == 1:
return 0
if n == 2:
return 0 if A[0]>=A[1] else 1
if A[n//2]>=A[n//2 + 1] and A[n//2]>=A[n//2 - 1]:
return n//2
elif A[n//2 - 1]>=A[n//2]:
return peak_recursive(A[0:n//2])
else:
return n//2+1+peak_recursive(A[n//2+1:])
\end{compactlisting}
\end{frame}
\end{document}
然而左边的数字与封闭的框重叠:
如何修复此问题?
(作为次要问题,是否可以控制制表符的缩进程度,以便例如第 2 行的缩进较少?)
答案1
You can set the margin with tcolorbox keys:
\documentclass[11pt]{beamer}
\usepackage{tcolorbox}
\tcbuselibrary{listings,skins}
\lstdefinestyle{compactstyle}{
numbers=left,
numberstyle=\small,
numbersep=8pt,
language=Python,
basicstyle=\tiny,
}
\newtcblisting{compactlisting}[2][]{
arc=0pt, outer arc=0pt,
listing only,
listing style=compactstyle,
title=#2,
left=1cm,%<------------ adapt
#1
}
\usepackage{listings,newtxtt}
\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}
\begin{document}
\begin{frame}[fragile]
\frametitle{Title}
\begin{compactlisting}[hbox]{}
def peak_recursive(A):
n = len(A)
if n == 1:
return 0
if n == 2:
return 0 if A[0]>=A[1] else 1
if A[n//2]>=A[n//2 + 1] and A[n//2]>=A[n//2 - 1]:
return n//2
elif A[n//2 - 1]>=A[n//2]:
return peak_recursive(A[0:n//2])
else:
return n//2+1+peak_recursive(A[n//2+1:])
\end{compactlisting}
\end{frame}
\end{document}