I’d like to have a solution environment that does the following:
- It writes the contents of the environment to an external file
\jobname.py. All the solutions should be in the same file\jobname.py. - The content of this environment (the solution) will be Python code and will include
#characters and tab characters. The solution should not be displayed in the PDF, it should only be written in the external file. - (If writing actual tab characters isn’t possible, I can work around it by replacing tabs with consecutive spaces.)
- Before writing the environment’s contents to
\jobname.py, it should before write in\jobname.pythe following line:
## Exercise \numberExercise,
where \numberExercise is a macro that returns the exercise number (I will define this macro, but for testing you can assume \def\numberExercise{2.1}).
The goal of this environment is to put directly the solutions to the exercises in my LaTeX document and to be able to create a .py file from the .tex document.
I tried to write this environment but couldn’t get it to work.
Could you help me?
Please feel free to ask if anything is unclear.
Here is a MWE:
\documentclass{article} \def\numberExercise{2.1} \newenvironment{solution} {...} {...} \begin{document} Write a function \texttt{facto(n)} that returns the factorial of $n$. \begin{solution} # We proceed recursively def facto(n): if n == 0: return 1 else: return facto(n-1)*n \end{solution} \end{document} 