在同一两栏文章中包含 Python 和 R 代码

在同一两栏文章中包含 Python 和 R 代码

我有 bench ohPythonR代码,我想将其插入到我的 LaTeX 文章中。我如何包含 .py 或 .r 代码文件?我以前用 Matlab 做过这样的事情:

\begin{center}
\begin{figure} 
\caption{come caption. \label{fig:cod1}}
\lstinputlisting{code/test.m}
\end{figure}
\end{center}

但是,这次我有一篇双栏文章,我想换行。

答案1

以下是示例代码运行。我使用了“listings”、“filecontents”和“multicol”包

\documentclass[12pt]{article}
\usepackage{filecontents}
\usepackage{listings}
\usepackage[margin=1in]{geometry}
\usepackage{multicol}

\begin{document}
\begin{multicols}{2}
\begin{filecontents*}{matlabcode.tex}
while (~feof(fileID))                               

   fprintf('Block: %s\n', num2str(Block))           
   InputText = textscan(fileID,'%s',2,
      'delimiter','\n');  
   HeaderLines{Block,1} = InputText{1};
   disp(HeaderLines{Block});                        

   InputText = textscan(fileID,'Num SNR = %f');     

   NumCols = InputText{1};                             

   FormatString = repmat('%f',1,NumCols);           

   InputText = textscan(fileID,FormatString, ...    
      'delimiter',',');

   Data{Block,1} = cell2mat(InputText);              
   [NumRows,NumCols] = size(Data{Block});           
   disp(cellstr(['Table data size: ' ...
      num2str(NumRows) ' x ' num2str(NumCols)]));
   disp(' ');                                          

   eob = textscan(fileID,'%s',1,
      'delimiter','\n');  
   Block = Block+1;                                
end
\end{filecontents*}

\begin{filecontents*}{pythoncode.tex}
prices = {'apple': 0.40, 'banana': 0.50}
my_purchase = {
    'apple': 1,
    'banana': 6}
grocery_bill = sum(prices[fruit] 
                 * my_purchase[fruit]
                 for fruit in my_purchase)
print 'I owe the grocer $%.2f'  grocery_bill
\end{filecontents*}%$

\begin{filecontents*}{'rcode.R'}
#utility functions

readinteger <- function()
{ 
  n <- readline(prompt="Enter an integer: ")
  if(!grepl("^[0-9]+$",n)) #$
  {
    return(readinteger())
  }
  return(as.integer(n))
}

# real program start here

num <- round(runif(1) * 100, digits = 0)
guess <- -1

cat("Guess a number between 0 and 100.\n")

while(guess != num)
{ 
  guess <- readinteger()
  if (guess == num)
  {
    cat("Congratulations,", num, "is right.\n")
  }
  else if (guess < num)
  {
    cat("It's bigger!\n")
  }
  else if(guess > num)
  {
    cat("It's smaller!\n")
  }
}
\end{filecontents*}

{\Huge matlab}
\tiny
\lstinputlisting[language=matlab]{matlabcode.tex}
{\Huge python}
\tiny
\lstinputlisting[language=Python]{pythoncode.tex}
{\Huge R}
\tiny

\lstinputlisting[language=R]{rcode.tex}

\end{multicols}
\end{document}

输出为:

在此处输入图片描述

相关内容