diff --git a/.gitignore b/.gitignore index 6ace9fc9..efd915fd 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,11 @@ __pycache__/ # C extensions *.so +# Latex compilation files +*.fdb_latexmk +*.fls +*.pdf.version + # Distribution / packaging .Python develop-eggs/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 7341cc68..402e0804 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,2 +1,4 @@ -FIX wrong example for D01 ex03 "vector" +- One file per exercise +- Indentation fixes +- Makefile update to clean latex compilation files diff --git a/Makefile b/Makefile index f0aeeee8..d828fdc8 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,7 @@ all: clean dirs %.pdf: @echo "We are taking care of: $@" @$(MAKE) -C $(shell dirname $@) + @$(MAKE) clean -C $(shell dirname $@) cp $@ build/$(shell dirname `dirname $@`).pdf dirs: $(TARGETS_DIRS) diff --git a/build/module00.pdf b/build/module00.pdf index 4727da66..da4fee1e 100644 Binary files a/build/module00.pdf and b/build/module00.pdf differ diff --git a/build/module01.pdf b/build/module01.pdf index 670d75b8..c2f9826f 100644 Binary files a/build/module01.pdf and b/build/module01.pdf differ diff --git a/build/module02.pdf b/build/module02.pdf index 257956c3..a4721434 100644 Binary files a/build/module02.pdf and b/build/module02.pdf differ diff --git a/build/module03.pdf b/build/module03.pdf index 73661658..aa129ce8 100644 Binary files a/build/module03.pdf and b/build/module03.pdf differ diff --git a/build/module04.pdf b/build/module04.pdf index 0f7e70a5..7fb0ef71 100644 Binary files a/build/module04.pdf and b/build/module04.pdf differ diff --git a/module00/subject/en.acknowledgements.tex b/module00/subject/en.acknowledgements.tex new file mode 100644 index 00000000..b6fdd85e --- /dev/null +++ b/module00/subject/en.acknowledgements.tex @@ -0,0 +1,38 @@ +\section*{Contact} +% --------------------------------- % +You can contact 42AI by email: \href{mailto:contact@42ai.fr}{contact@42ai.fr}\\ +\newline +Thank you for attending 42AI's Python Bootcamp module00 ! + +% ================================= % +\section*{Acknowledgements} +% --------------------------------- % +The Python bootcamp is the result of a collective work, for which we would like to thank: +\begin{itemize} + \item Maxime Choulika (cmaxime), + \item Pierre Peigné (ppeigne, pierre@42ai.fr), + \item Matthieu David (mdavid, matthieu@42ai.fr), + \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) + \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) +\end{itemize} +who supervised the creation, the enhancement of the bootcamp and this present transcription. + +\begin{itemize} + \item Louis Develle (ldevelle, louis@42ai.fr) + \item Augustin Lopez (aulopez) + \item Luc Lenotre (llenotre) + \item Owen Roberts (oroberts) + \item Thomas Flahault (thflahau) + \item Amric Trudel (amric@42ai.fr) + \item Baptiste Lefeuvre (blefeuvr@student.42.fr) + \item Mathilde Boivin (mboivin@student.42.fr) + \item Tristan Duquesne (tduquesn@student.42.fr) +\end{itemize} +for your investment in the creation and development of these modules. + +\begin{itemize} + \item All prior participants who took a moment to provide their feedbacks, and help us improve these bootcamps ! +\end{itemize} + + \vfill +\doclicenseThis \ No newline at end of file diff --git a/module00/subject/en.py_proj.tex b/module00/subject/en.instructions.tex similarity index 81% rename from module00/subject/en.py_proj.tex rename to module00/subject/en.instructions.tex index 4088b2c5..8a1bd0c6 100644 --- a/module00/subject/en.py_proj.tex +++ b/module00/subject/en.instructions.tex @@ -24,9 +24,8 @@ \chapter{Common Instructions} on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your questions to your peers in the dedicated Bootcamp channel. - \item You can also ask questions in the \texttt{\#bootcamps} channel on Slack at \href{https://42-ai.slack.com}{42AI} - or \href{42born2code.slack.com}{42born2code}. - + \item You can learn more about 42 Artificial Intelligence by visiting \href{https://42-ai.github.io}{our website}. + \item If you find any issue or mistake in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. \item We encourage you to create test programs for your @@ -36,10 +35,9 @@ \chapter{Common Instructions} those tests especially useful during your defence. Indeed, during defence, you are free to use your tests and/or the tests of the peer you are evaluating. - - \item Submit your work to your assigned git repository. Only the work in the - git repository will be graded. If Deepthought is assigned to grade your - work, it will be run after your peer-evaluations. - If an error happens in any section of your work during Deepthought's grading, - the evaluation will stop. + + \item We are constantly looking to improve these bootcamps, and your feedbacks are essential for us to do so !\\ + You can tell us more about your experience with this module by filling \href{https://forms.gle/89TZJDARdgZfghRPA}{this form}.\\ + Thank you in advance and good luck for this bootcamp ! + \end{itemize} \ No newline at end of file diff --git a/module00/subject/en.subject.aux b/module00/subject/en.subject.aux deleted file mode 100644 index b6401217..00000000 --- a/module00/subject/en.subject.aux +++ /dev/null @@ -1,2 +0,0 @@ -\relax -\gdef \@abspage@last{1} diff --git a/module00/subject/en.subject.fdb_latexmk b/module00/subject/en.subject.fdb_latexmk deleted file mode 100644 index 48c40300..00000000 --- a/module00/subject/en.subject.fdb_latexmk +++ /dev/null @@ -1,15 +0,0 @@ -# Fdb version 4 -["pdflatex"] 1727451362.26515 "/home/gh0st/Bureau/ci_cd_exp/module00/subject/en.subject.tex" "en.subject.pdf" "en.subject" 1727451362.45958 2 - "/etc/texmf/web2c/texmf.cnf" 1727339314.10574 475 c0e671620eb5563b2130f56340a5fde8 "" - "/home/gh0st/Bureau/ci_cd_exp/module00/subject/en.subject.tex" 1727451361.85004 31529 c866b527f26d4aa6c1c80e3580763fbc "" - "/usr/share/texlive/texmf-dist/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/usr/share/texmf/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/var/lib/texmf/web2c/pdftex/pdflatex.fmt" 1727356375 8215269 fd93dc40f384268405c8bca19f4d73c2 "" - "42-en.cls" 0 -1 0 "" - "en.subject.aux" 1727451362.26405 32 3985256e7290058c681f74d7a3565a19 "pdflatex" - "en.subject.tex" 1727451361.85004 31529 c866b527f26d4aa6c1c80e3580763fbc "" - (generated) - "en.subject.aux" - "en.subject.log" - "en.subject.pdf" - (rewritten before read) diff --git a/module00/subject/en.subject.fls b/module00/subject/en.subject.fls deleted file mode 100644 index 1aa541df..00000000 --- a/module00/subject/en.subject.fls +++ /dev/null @@ -1,7 +0,0 @@ -PWD /home/gh0st/Bureau/ci_cd_exp/module00/subject -INPUT /etc/texmf/web2c/texmf.cnf -INPUT /usr/share/texmf/web2c/texmf.cnf -INPUT /usr/share/texlive/texmf-dist/web2c/texmf.cnf -INPUT /var/lib/texmf/web2c/pdftex/pdflatex.fmt -INPUT /home/gh0st/Bureau/ci_cd_exp/module00/subject/en.subject.tex -OUTPUT en.subject.log diff --git a/module00/subject/en.subject.pdf b/module00/subject/en.subject.pdf index 4727da66..da4fee1e 100644 Binary files a/module00/subject/en.subject.pdf and b/module00/subject/en.subject.pdf differ diff --git a/module00/subject/en.subject.pdf.version b/module00/subject/en.subject.pdf.version deleted file mode 100644 index 56a6051c..00000000 --- a/module00/subject/en.subject.pdf.version +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/module00/subject/en.subject.pyg b/module00/subject/en.subject.pyg deleted file mode 100644 index 5d11ad53..00000000 --- a/module00/subject/en.subject.pyg +++ /dev/null @@ -1,112 +0,0 @@ - -\makeatletter -\def\PY@reset{\let\PY@it=\relax \let\PY@bf=\relax% - \let\PY@ul=\relax \let\PY@tc=\relax% - \let\PY@bc=\relax \let\PY@ff=\relax} -\def\PY@tok#1{\csname PY@tok@#1\endcsname} -\def\PY@toks#1+{\ifx\relax#1\empty\else% - \PY@tok{#1}\expandafter\PY@toks\fi} -\def\PY@do#1{\PY@bc{\PY@tc{\PY@ul{% - \PY@it{\PY@bf{\PY@ff{#1}}}}}}} -\def\PY#1#2{\PY@reset\PY@toks#1+\relax+\PY@do{#2}} - -\@namedef{PY@tok@}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@w}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@err}{\def\PY@tc##1{\textcolor[rgb]{0.59,0.00,0.31}{##1}}\def\PY@bc##1{{\setlength{\fboxsep}{0pt}\colorbox[rgb]{0.12,0.00,0.06}{\strut ##1}}}} -\@namedef{PY@tok@x}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@c}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@cm}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@cp}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@c1}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@cs}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@k}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@kc}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@kd}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@kn}{\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@kp}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@kr}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@kt}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@o}{\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@ow}{\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@p}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@n}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@na}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@nb}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@bp}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@nc}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@no}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@nd}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@ni}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@ne}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@nf}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@py}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@nl}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@nn}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@nx}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@nt}{\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@nv}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@vc}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@vg}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@vi}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@l}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@m}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@mf}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@mh}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@mi}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@il}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@mo}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@ld}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@s}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@sb}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@sc}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@sd}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@s2}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@se}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@sh}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@si}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@sx}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@sr}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@s1}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@ss}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@g}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@gd}{\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@ge}{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@gr}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@gh}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@gi}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@go}{\def\PY@tc##1{\textcolor[rgb]{0.40,0.85,0.94}{##1}}} -\@namedef{PY@tok@gp}{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.98,0.15,0.45}{##1}}} -\@namedef{PY@tok@gs}{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@gu}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@gt}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@esc}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@fm}{\def\PY@tc##1{\textcolor[rgb]{0.65,0.89,0.18}{##1}}} -\@namedef{PY@tok@vm}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@sa}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@dl}{\def\PY@tc##1{\textcolor[rgb]{0.90,0.86,0.45}{##1}}} -\@namedef{PY@tok@mb}{\def\PY@tc##1{\textcolor[rgb]{0.68,0.51,1.00}{##1}}} -\@namedef{PY@tok@pm}{\def\PY@tc##1{\textcolor[rgb]{0.97,0.97,0.95}{##1}}} -\@namedef{PY@tok@ch}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} -\@namedef{PY@tok@cpf}{\def\PY@tc##1{\textcolor[rgb]{0.46,0.44,0.37}{##1}}} - -\def\PYZbs{\char`\\} -\def\PYZus{\char`\_} -\def\PYZob{\char`\{} -\def\PYZcb{\char`\}} -\def\PYZca{\char`\^} -\def\PYZam{\char`\&} -\def\PYZlt{\char`\<} -\def\PYZgt{\char`\>} -\def\PYZsh{\char`\#} -\def\PYZpc{\char`\%} -\def\PYZdl{\char`\$} -\def\PYZhy{\char`\-} -\def\PYZsq{\char`\'} -\def\PYZdq{\char`\"} -\def\PYZti{\char`\~} -% for compatibility with earlier versions -\def\PYZat{@} -\def\PYZlb{[} -\def\PYZrb{]} -\makeatother - diff --git a/module00/subject/en.subject.tex b/module00/subject/en.subject.tex index 807f6e1d..c145b2c6 100644 --- a/module00/subject/en.subject.tex +++ b/module00/subject/en.subject.tex @@ -93,1000 +93,74 @@ } \makeatother - \begin{document} % =============================================================================% % ===================================== % -\title{Python \& ML - Module 00} +\title{Python Bootcamp - Module 00} \subtitle{Basic stuff - The Eleven Commandments} -\author{ - Maxime Choulika (cmaxime), Pierre Peigné (ppeigne), Matthieu David (mdavid) -} - -\summary -{ - The goal of the module is to get started with the Python language. -} - +\author{} +\summary{The goal of this module is to get you started with Python} \maketitle -\input{en.py_proj.tex} +\input{en.instructions.tex} \newpage \tableofcontents \startexercices - % ===================================== % % =============================================================================% - - %******************************************************************************% % % % Exercises % % % %******************************************************************************% -% ============================================== % % ===========================(start ex 00) % -\chapter{Exercise 00} -\extitle{\$PATH} -\turnindir{ex00} -\exnumber{00} -\exfiles{answers.txt, requirements.txt} -\exforbidden{None} -\makeheaderfilesforbidden - -\emph{The first thing you need to do is install Python.} -\\\\ -Most modern Unix-based systems have a \texttt{python} interpreter installed by default, -but its version might be lower/higher than the one used for these modules. -It is also possible that the default \texttt{python} command uses a version 2.x (for legacy reasons). -This is obviously very confusing for a new developper. -\\ - -\begin{42console} -$> python -V -$> python3 -V -\end{42console} -\hfill \break -To deal with those version issues we will use \texttt{conda}. This program allows you to manage your Python packages and several working environments. -\\\\ -\emph{Note: the actual requirement is to use a Python 3.7.X version. You are free to use a different program/utilities to achieve this goal. At your own risk.} -\pagebreak - -% ===========================(Conda Manual) % -\section*{Conda manual installation} -\emph{Go to the next section for an automated installation.} -\\\\ -We recommend the following path for your \texttt{conda} folder. -\begin{42console} -$> MYPATH="/goinfre/$USER/miniconda3" -\end{42console} - -% ---------------------------------- % -\subsection*{1. Download \& Install conda} - -\begin{42console} -# For MAC -$> curl -LO "https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh" -$> sh Miniconda3-latest-MacOSX-x86_64.sh -b -p $MYPATH - -# For Linux -$> curl -LO "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh" -$> sh Miniconda3-latest-Linux-x86_64.sh -b -p $MYPATH -\end{42console} - - - -% ---------------------------------- % -\subsection*{2. Initial configuration of conda} -\begin{42console} -# For zsh -$> $MYPATH/bin/conda init zsh -$> $MYPATH/bin/conda config --set auto_activate_base false -$> source ~/.zshrc - -# For bash -$> $MYPATH/bin/conda init bash -$> $MYPATH/bin/conda config --set auto_activate_base false -$> source ~/.bash_profile -\end{42console} - - - -% ---------------------------------- % -\subsection*{3. Create a dedicated environment for 42AI !} -\begin{42console} -$> conda create --name 42AI-$USER python=3.7 jupyter pandas pycodestyle numpy -\end{42console} - - - -% ---------------------------------- % -\subsection*{4. Check your 42AI Python environment} -\begin{42console} -$> conda info --envs -$> conda activate 42AI-$USER -$> which python -$> python -V -$> python -c "print('Hello World!')" -\end{42console} - - - -% ---------------------------------- % -\subsection*{Help !} -\begin{itemize} - \item \textbf{I have lost my miniconda3 folder !} Repeat step 1 and 3. - \item \textbf{I have lost my home directory !} Repeat step 2. -\end{itemize} -\pagebreak - - - -% ===========================(Conda Auto) % -\section*{Conda automated installation} - -Copy the following script into a file, launch it and follow the instructions. It downloads and installs miniconda in a \texttt{/goinfre} subfolder and creates a \texttt{python} environment in \texttt{conda}. - - -\begin{42console} -#!/bin/bash - -function which_dl { - # If operating system name contains Darwnin: MacOS. Else Linux - if uname -s | grep -iqF Darwin; then - echo "Miniconda3-latest-MacOSX-x86_64.sh" - else - echo "Miniconda3-latest-Linux-x86_64.sh" - fi -} - -function which_shell { - # if $SHELL contains zsh, zsh. Else Bash - if echo $SHELL | grep -iqF zsh; then - echo "zsh" - else - echo "bash" - fi -} - -function when_conda_exist { - # check and install 42AI environement - printf "Checking 42AI-$USER environment: " - if conda info --envs | grep -iqF 42AI-$USER; then - printf "\e[33mDONE\e[0m\n" - else - printf "\e[31mKO\e[0m\n" - printf "\e[33mCreating 42AI environnment:\e[0m\n" - conda update -n base -c defaults conda -y - conda create --name 42AI-$USER python=3.7 jupyter numpy pandas pycodestyle -y - fi -} - -function set_conda { - MINICONDA_PATH="/goinfre/$USER/miniconda3" - CONDA=$MINICONDA_PATH"/bin/conda" - PYTHON_PATH=$(which python) - REQUIREMENTS="jupyter numpy pandas pycodestyle" - SCRIPT=$(which_dl) - MY_SHELL=$(which_shell) - DL_LINK="https://repo.anaconda.com/miniconda/"$SCRIPT - DL_LOCATION="/tmp/" - - printf "Checking conda: " - TEST=$(conda -h 2>/dev/null) - if [ $? == 0 ] ; then - printf "\e[32mOK\e[0m\n" - when_conda_exist - return - fi - printf "\e[31mKO\e[0m\n" - if [ ! -f $DL_LOCATION$SCRIPT ]; then - printf "\e[33mDonwloading installer:\e[0m\n" - cd $DL_LOCATION - curl -LO $DL_LINK - cd - - fi - printf "\e[33mInstalling conda:\e[0m\n" - sh $DL_LOCATION$SCRIPT -b -p $MINICONDA_PATH - printf "\e[33mConda initial setup:\e[0m\n" - $CONDA init $MY_SHELL - $CONDA config --set auto_activate_base false - - printf "\e[33mCreating 42AI-$USER environnment:\e[0m\n" - $CONDA update -n base -c defaults conda -y - $CONDA create --name 42AI-$USER python=3.7 jupyter numpy pandas pycodestyle -y - printf "\e[33mLaunch the following command or restart your shell:\e[0m\n" - if [ $MY_SHELL == "zsh" ]; then - printf "\tsource ~/.zshrc\n" - else - printf "\tsource ~/.bash_profile\n" - fi -} - -set_conda -\end{42console} -\hfill \break -Don't forget to check your 42AI Python environment ! -\begin{42console} -conda info --envs -conda activate 42AI-$USER -which python -python -V -python -c "print('Hello World!')" -\end{42console} -\newpage - - - -% =================================(Question) % -\section*{(Finally) getting started} - -Now that your setup is ready to run, here are a few questions that need to be solved using \texttt{python}, \texttt{pip} or \texttt{conda}. Save your answers in a file \texttt{answers.txt} (one answer per line and per question), and check them with your peers.\\\\ -Find the commands to: -\begin{itemize} - \item Output a list of installed packages and their versions. - \item Show the package metadata of \texttt{numpy}. - \item Remove the package \texttt{numpy}. - \item (Re)install the package \texttt{numpy}. - \item Freeze your \texttt{python} packages and their versions in a \texttt{requirements.txt} file you have to turn-in. -\end{itemize} - - +\input{exercises/m00ex00.tex} % ===========================(fin ex 00) % \newpage % ===========================(start ex 01) % -\chapter{Exercise 01} -\extitle{Rev Alpha} -\turnindir{ex01} -\exnumber{01} -\exfiles{exec.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -% \section*{} -Make a program that takes a string as argument, reverses it, swaps its letters case and prints the result. -\begin{itemize} - \item If more than one argument is provided, merge them into a single string with each argument separated by a single space character. - \item If no argument is provided, do nothing or print an usage. -\end{itemize} - - -% --------------------------------- % -\section*{Examples} - -\begin{42console} -$> python3 exec.py 'Hello World!' | cat -e -!DLROw OLLEh$ -$> -$> python3 exec.py 'Hello' 'my Friend' | cat -e -DNEIRf YM OLLEh$ -$> -$> python3 exec.py -$> -\end{42console} - +\input{exercises/m00ex01.tex} % ===========================(fin ex 01) % \newpage % ===========================(start ex 02) % -\chapter{Exercise 02} -\extitle{The Odd, the Even and the Zero} -\turnindir{ex02} -\exnumber{02} -\exfiles{whois.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -% \section*{} -Make a program that takes a number as argument, checks whether it is odd, even or zero, and prints the result. -\begin{itemize} - \item If more than one argument is provided or if the argument is not an integer, print an error message. - \item If no argument is provided, do nothing or print an usage. -\end{itemize} - - -% --------------------------------- % -\section*{Examples} -\begin{42console} -$> python3 whois.py 12 -I'm Even. -$> -$> python3 whois.py 3 -I'm Odd. -$> -$> python3 whois.py -$> -$> python3 whois.py 0 -I'm Zero. -$> -$> python3 whois.py Hello -AssertionError: argument is not an integer -$> -$> python3 whois.py 12 3 -AssertionError: more than one argument is provided -$> -\end{42console} - -\hint{ - No bonus point to be gained from a complex error management system. Keep it simple. -} - +\input{exercises/m00ex02.tex} % ===========================(fin ex 02) % \newpage % ===========================(start ex 03) % -\chapter{Exercise 03} -\extitle{Functional file} -\turnindir{ex03} -\exnumber{03} -\exfiles{count.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Part 1. text\_analyzer} -Create a function called \texttt{text\_analyzer} that takes a single string argument -and displays the total number of printable characters, and respectively : the number of upper-case characters, lower-case characters, punctuation characters and spaces. -\begin{itemize} - \item If \texttt{None} or nothing is provided, the user is prompted to provide a string. - \item If the argument is not a string, print an error message. - \item This function must have a \texttt{docstring} explaning its behavior. -\end{itemize} - -Test your function with the \texttt{python} console - -% --------------------------------- % -\subsection*{Examples} -\begin{42console} -$> python3 ->>> from count import text_analyzer ->>> text_analyzer("Python 2.0, released 2000, introduced -features like List comprehensions and a garbage collection -system capable of collecting reference cycles.") -The text contains 143 printable character(s): -- 2 upper letter(s) -- 113 lower letter(s) -- 4 punctuation mark(s) -- 18 space(s) ->>> text_analyzer("Python is an interpreted, high-level, -general-purpose programming language. Created by Guido van -Rossum and first released in 1991, Python's design philosophy -emphasizes code readability with its notable use of significant -whitespace.") -The text contains 234 printable character(s): -- 5 upper letter(s) -- 187 lower letter(s) -- 8 punctuation mark(s) -- 30 space(s) ->>> text_analyzer() -What is the text to analyze? ->> Hello World! -The text contains 12 printable character(s): -- 2 upper letter(s) -- 8 lower letter(s) -- 1 punctuation mark(s) -- 1 space(s) ->>> text_analyzer(42) -AssertionError: argument is not a string ->>> print(text_analyzer.__doc__) - - This function counts the number of upper characters, lower characters, - punctuation and spaces in a given text. -\end{42console} - -% ================================= % -\section*{Part 2. \_\_name\_\_==\_\_main\_\_} - - -In the previous part, you wrote a function that can be used in the console or in another file when imported. -Without changing this behavior, update your file so it can also be launched as a standalone program. - -\begin{itemize} - \item If more than one argument is provided to the program, print an error message. - \item Otherwise, use the \texttt{text\_analyzer} function. -\end{itemize} - -% --------------------------------- % -\subsection*{Examples} -\begin{42console} -$> python3 count.py 'Hello World!' -The text contains 12 character(s): -- 2 upper letter(s) -- 8 lower letter(s) -- 1 punctuation mark(s) -- 1 space(s) -$> python3 ->>> from count import text_analyzer ->>> text_analyzer("Hello World!") -The text contains 12 character(s): -- 2 upper letter(s) -- 8 lower letter(s) -- 1 punctuation mark(s) -- 1 space(s) -\end{42console} - +\input{exercises/m00ex03.tex} % ===========================(fin ex 03) % \newpage % ===========================(start ex 04) % -\chapter{Exercise 04} -\extitle{Elementary} -\turnindir{ex04} -\exnumber{04} -\exfiles{operations.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -% \section*{} -Write a program that takes two integers A and B as arguments and prints the result of the following operations: -\begin{42console} -Sum: A+B -Difference: A-B -Product: A*B -Quotient: A/B -Remainder: A%B -\end{42console} - -\begin{itemize} - \item If more or less than two arguments are provided or if one of the arguments is not an integer, print an error message. - \item If no argument is provided, do nothing or print an usage. - \item If an operation is impossible, print an error message instead of a numerical result. -\end{itemize} - -% ================================= % -\section*{Examples} -\begin{42console} -$> python3 operations.py 10 3 -Sum: 13 -Difference: 7 -Product: 30 -Quotient: 3.3333... -Remainder: 1 -$> -$> python3 operations.py 42 10 -Sum: 52 -Difference: 32 -Product: 420 -Quotient: 4.2 -Remainder: 2 -$> -$> python3 operations.py 1 0 -Sum: 1 -Difference: 1 -Product: 0 -Quotient: ERROR (division by zero) -Remainder: ERROR (modulo by zero) -$> -$> python3 operations.py -Usage: python operations.py -Example: - python operations.py 10 3 -$> -$> python3 operations.py 12 10 5 -AssertionError: too many arguments -$> -$> python3 operations.py "one" "two" -AssertionError: only integers -$> -\end{42console} - -\hint{ - No bonus point to be gained from handling decimal point or scientific notation. Keep it simple. -} - +\input{exercises/m00ex04.tex} % ===========================(fin ex 04) % \newpage % ===========================(start ex 05) % - -\chapter{Exercise 05} -\extitle{The right format} -\turnindir{ex05} -\exnumber{05} -\exfiles{kata00.py, kata01.py, kata02.py, kata03.py, kata04.py} -\exforbidden{None} -\makeheaderfilesforbidden - -Let's get familiar with the useful concept of \textbf{string formatting} through a kata series.\\ - -Each exercice will provide you with a \texttt{kata} variable. This variable can be modified to a certain extent: your program must react accordingly. - -% ================================= % -\section*{kata00} -The \texttt{kata} variable is always a tuple and can only be filled with integers. -\begin{42console} -# Put this at the top of your kata00.py file -kata = (19,42,21) -\end{42console} - -Write a program that displays this variable content according to the format shown below: - -\begin{42console} -$> python3 kata00.py -The 3 numbers are: 19, 42, 21 -$> -\end{42console} - -% ================================= % -\section*{kata01} - -The \texttt{kata} variable is always a dictionary and can only be filled with strings. - -\begin{42console} -# Put this at the top of your kata01.py file -kata = { - 'Python': 'Guido van Rossum', - 'Ruby': 'Yukihiro Matsumoto', - 'PHP': 'Rasmus Lerdorf', - } -\end{42console} - -Write a program that displays this variable content according to the format shown below: - -\begin{42console} -$> python3 kata01.py -Python was created by Guido van Rossum -Ruby was created by Yukihiro Matsumoto -PHP was created by Rasmus Lerdorf -$> -\end{42console} - -% ================================= % -\section*{kata02} - -The \texttt{kata} variable is always a tuple that contains 5 non-negative integers. The first integer contains up to 4 digits, the rest up to 2 digits. - -\begin{42console} -# Put this at the top of your kata02.py file -kata = (2019, 9, 25, 3, 30) -\end{42console} - -Write a program that displays this variable content according to the format shown below: - -\begin{42console} -$> python3 kata02.py | cat -e -09/25/2019 03:30$ -$> python3 kata02.py | wc -c -17 -$> -\end{42console} - -% ================================= % -\section*{kata03} - -The \texttt{kata} variable is always a string whose length is not higher than 42. - -\begin{42console} -# Put this at the top of your kata03.py file -kata = "The right format" -\end{42console} - -Write a program that displays this variable content according to the format shown below: - -\begin{42console} -$> python3 kata03.py | cat -e ---------------------------The right format% -$> python3 kata03.py | wc -c -42 -$> -\end{42console} - -% ================================= % -\section*{kata04} - -The \texttt{kata} variable is always a tuple that contains, in the following order: -\begin{itemize} - \item 2 non-negative integers containing up to 2 digits - \item 1 decimal - \item 1 integer - \item 1 decimal -\end{itemize} - -\begin{42console} -# Put this at the top of your kata04.py file -kata = (0, 4, 132.42222, 10000, 12345.67) -\end{42console} - -Write a program that displays this variable content according to the format shown below: - -\begin{42console} -$> python3 kata04.py -module_00, ex_04 : 132.42, 1.00e+04, 1.23e+04 -$> python3 kata04.py | cut -c 10,18 -,: -\end{42console} - +\input{exercises/m00ex05.tex} % ===========================(fin ex 05) % \newpage % ===========================(start ex 06) % -\chapter{Exercise 06} -\extitle{A recipe} -\turnindir{ex06} -\exnumber{06} -\exfiles{recipe.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================= % -\section*{Part 1: Nested Dictionaries} - -Create a dictionary called \texttt{cookbook}. You will use this \texttt{cookbook} to store recipes. -\\\\ -A recipe is a \textbf{dictionary} that stores (at least) 3 key-value pairs: -\begin{itemize} - \item ''ingredients": a \textbf{list of strings} containing the list of ingredients - \item "meal": a \textbf{string} representing the type of meal - \item "prep\_time": a \textbf{non-negative integer} representing a preparation time in minutes -\end{itemize} - -In the \texttt{cookbook}, the \textbf{key} to a recipe is the recipe's name. -\\ -Initialize your \texttt{cookbook} with 3 recipes: -\begin{itemize} - \item The Sandwich's ingredients are \textit{ham}, \textit{bread}, \textit{cheese} and \textit{tomatoes}. -It is a \textit{lunch} and it takes $10$ minutes of preparation. - \item The Cake's ingredients are \textit{flour}, \textit{sugar} and \textit{eggs}. -It is a \textit{dessert} and it takes $60$ minutes of preparation. - \item The Salad's ingredients are \textit{avocado}, \textit{arugula}, \textit{tomatoes} and \textit{spinach}. -It is a \textit{lunch} and it takes $15$ minutes of preparation. -\end{itemize} - -% ================================= % -\section*{Part 2: A Handful of Helpful Functions} - -Create a series of useful functions to handle your \texttt{cookbook}: - -\begin{enumerate} - \item A function that prints all recipe names. - \item A function that takes a recipe name and prints its details. - \item A function that takes a recipe name and delete it. - \item A function that adds a recipe from user input. You will need a name, a list of ingredients, a meal type and a preparation time. -\end{enumerate} -\subsection*{input example} -\begin{42console} ->>> Enter a name: -chips ->>> Enter ingredients: -potatoes -oil -salt - ->>> Enter a meal type: -lunch ->>> Enter a preparation time: -15 -\end{42console} - -% ================================= % -\section*{Part 3: A command line executable !} - -Create a program that uses your \texttt{cookbook} and your functions.\\ - -The program will prompt the user to make a choice between printing the cookbook's content, printing one recipe, adding a recipe, deleting a recipe or quitting the cookbook.\\ - -Your program will continue to prompt the user until the user decides to quit it. - -The program cannot crash if a wrong value is entered: you must handle the error and ask for another prompt. - -\begin{42console} -$> python3 recipe.py -Welcome to the Python Cookbook ! -List of available options: - 1: Add a recipe - 2: Delete a recipe - 3: Print a recipe - 4: Print the cookbook - 5: Quit - -Please select an option: ->> 3 - -Please enter a recipe name to get its details: ->> cake - -Recipe for cake: - Ingredients list: ['flour', 'sugar', 'eggs'] - To be eaten for dessert. - Takes 60 minutes of cooking. - -Please select an option: ->> Hello - -Sorry, this option does not exist. -List of available options: - 1: Add a recipe - 2: Delete a recipe - 3: Print a recipe - 4: Print the cookbook - 5: Quit - -Please select an option: ->> 5 - -Cookbook closed. Goodbye ! -$> -\end{42console} - - +\input{exercises/m00ex06.tex} % ===========================(fin ex 06) % \newpage % ===========================(start ex 07) % -\chapter{Exercise 07} -\extitle{Shorter, faster, pythonic} -\turnindir{ex07} -\exnumber{07} -\exfiles{filterwords.py} -\exforbidden{filter} -\makeheaderfilesforbidden - -Make a program that takes a string S and an integer N as argument and prints the list of words in S that contains more than N non-punctuation characters. - -\begin{itemize} - \item Words are separated from each other by space characters - \item Punctuation symbols must be removed from the printed list: they are neither part of a word nor a separator - \item The program must contain at least one \textbf{list comprehension} expression. -\end{itemize} - -If the number of argument is different from 2, or if the type of any argument is invalid, the program prints an error message. - -% ================================= % -\section*{Examples} -% --------------------------------- % - -\begin{42console} -$> python3 filterwords.py 'Hello, my friend' 3 -['Hello', 'friend'] -$> python3 filterwords.py 'Hello, my friend' 10 -[] -$> python3 filterwords.py 'A robot must protect its own existence as long as such protection does not conflict with the First or Second Law' 6 -['protect', 'existence', 'protection', 'conflict'] -$> python3 filterwords.py Hello World -ERROR -$> python3 filterwords.py 3 'Hello, my friend' -ERROR -$> python3 filterwords.py -ERROR -\end{42console} - +\input{exercises/m00ex07.tex} % ===========================(fin ex 07) % \newpage % ===========================(start ex 08) % -\chapter{Exercise 08} -\extitle{S.O.S} -\turnindir{ex08} -\exnumber{08} -\exfiles{sos.py} -\exforbidden{None} -\makeheaderfilesforbidden - -Make a program that takes a string as argument and encodes it into Morse code. - -\begin{itemize} - \item The program supports space and alphanumeric characters - \item An alphanumeric character is represented by dots \texttt{.} and dashes \texttt{-}: - \item A space character is represented by a slash \texttt{/} - \item Complete morse characters are separated by a single space\\ -\end{itemize} - -If more than one argument is provided, merge them into a single string with each argument separated by a single space character.\\ - -If no argument is provided, do nothing or print an usage. - -% ================================= % -\section*{Examples} -\begin{42console} - $> python3 sos.py "SOS" - ... --- ... - $> python3 sos.py - $> python3 sos.py "HELLO / WORLD" - ERROR - $> python3 sos.py "96 BOULEVARD" "Bessiere" - ----. -.... / -... --- ..- .-.. . ...- .- .-. -.. / -... . ... ... .. . .-. . -\end{42console} - - -\hint{ - \url{https://morsecode.world/international/morse2.html} -} +\input{exercises/m00ex08.tex} % ===========================(fin ex 08) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 09) % -\chapter{Exercise 09} -\extitle{Secret number} -\turnindir{ex09} -\exnumber{09} -\exfiles{guess.py} -\exforbidden{None} -\makeheaderfilesforbidden - -You have to make a program that will be an interactive guessing game. -It will ask the user to guess a number between $1$ and $99$. -The program will tell the user if their input is too high or too low. -The game ends when the user finds out the secret number or types \texttt{exit}. -You will import the \texttt{random} module with the \texttt{randint} function to get a random number. -You have to count the number of trials and print that number when the user wins. - -% ================================= % -\section*{Examples} -% --------------------------------- % - -\begin{42console} - $> python guess.py - This is an interactive guessing game! - You have to enter a number between 1 and 99 to find out the secret number. - Type 'exit' to end the game. - Good luck! - - What's your guess between 1 and 99? - >> 54 - Too high! - What's your guess between 1 and 99? - >> 34 - Too low! - What's your guess between 1 and 99? - >> 45 - Too high! - What's your guess between 1 and 99? - >> A - That's not a number. - What's your guess between 1 and 99? - >> 43 - Congratulations, you've got it! - You won in 5 attempts! -\end{42console} - -If the user discovers the secret number on the first try, tell them. -If the secret number is 42, make a reference to Douglas Adams. - -\begin{42console} - $> python guess.py - This is an interactive guessing game! - You have to enter a number between 1 and 99 to find out the secret number. - Type 'exit' to end the game. - Good luck! - - What's your guess between 1 and 99? - >> 42 - The answer to the ultimate question of life, the universe and everything is 42. - Congratulations! You got it on your first try! -\end{42console} - - -Other example: - -\begin{42console} - $> python guess.py - This is an interactive guessing game! - You have to enter a number between 1 and 99 to find out the secret number. - Type 'exit' to end the game. - Good luck! - - What's your guess between 1 and 99? - >> exit - Goodbye! -\end{42console} - +\include{exercises/m00ex09.tex} % ===========================(fin ex 09) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 10) % -\chapter{Exercise 10} -\extitle{Loading bar!} -\turnindir{ex10} -\exnumber{10} -\exfiles{loading.py} -\exforbidden{\texttt{tqdm} or any library for automatic loading bar} -\makeheaderfilesforbidden - - -You are about to discover the \texttt{yield} operator! - -So let's create a function called \texttt{ft\_progress(lst)}. - -The function will display the progress of a \texttt{for} loop. - - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{42console}% SERAIT MIEUX AVEC UN ENVIRONNEMENT PYTHON - listy = range(1000) - ret = 0 - for elem in ft_progress(listy): - ret += (elem + 3) % 5 - sleep(0.01) - print() - print(ret) -\end{42console} - -\begin{42console} - $> python loading.py - ETA: 8.67s [ 23%][=====> ] 233/1000 | elapsed time 2.33s - ... - 2000 -\end{42console} - -\begin{42console}% SERAIT MIEUX AVEC UN ENVIRONNEMENT PYTHON - listy = range(3333) - ret = 0 - for elem in ft_progress(listy): - ret += elem - sleep(0.005) - print() - print(ret) -\end{42console} - -\begin{42console} - $> python loading.py - ETA: 14.67s [ 9%][=> ] 327/3333 | elapsed time 1.33s - ... - 5552778 -\end{42console} - -\info{We advise you to go take a look at the wonderful tqdm library, it will come in handy in many situations} - +\include{exercises/m00ex10.tex} % ===========================(fin ex 10) % -% ============================================== % \newpage % ================================= % -\section*{Contact} -% --------------------------------- % -You can contact 42AI association by email: contact@42ai.fr\\ - -If you are a student from 42, you can access our Discord server -on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your -questions to your peers in the dedicated Bootcamp channel. - -Find all the relevant and up-to-date information about 42AI on \href{https://42-ai.github.io}{our Website} ! - -Thank you for attending this Python Bootcamp module00 ! +\input{en.acknowledgements.tex} % ================================= % -\section*{Acknowledgements} -% --------------------------------- % -The modules Python \& ML is the result of a collective work, we would like to thank: -\begin{itemize} - \item Maxime Choulika (cmaxime), - \item Pierre Peigné (ppeigne, pierre@42ai.fr), - \item Matthieu David (mdavid, matthieu@42ai.fr), - \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) - \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) -\end{itemize} -who supervised the creation, the enhancement and this present transcription. - -\begin{itemize} - \item Louis Develle (ldevelle, louis@42ai.fr) - \item Augustin Lopez (aulopez) - \item Luc Lenotre (llenotre) - \item Owen Roberts (oroberts) - \item Thomas Flahault (thflahau) - \item Amric Trudel (amric@42ai.fr) - \item Baptiste Lefeuvre (blefeuvr@student.42.fr) - \item Mathilde Boivin (mboivin@student.42.fr) - \item Tristan Duquesne (tduquesn@student.42.fr) -\end{itemize} -for your investment for the creation and development of these modules. - -\begin{itemize} - \item Barthélémy Leveque (bleveque@student.42.fr) - \item Remy Oster (roster@student.42.fr) - \item Quentin Bragard (qbragard@student.42.fr) - \item Marie Dufourq (madufour@student.42.fr) - \item Adrien Vardon (advardon@student.42.fr) -\end{itemize} -who betatest the first version of the modules of Machine Learning. -\vfill -\doclicenseThis \end{document} diff --git a/module00/subject/exercises/m00ex00.tex b/module00/subject/exercises/m00ex00.tex new file mode 100644 index 00000000..1df99f1f --- /dev/null +++ b/module00/subject/exercises/m00ex00.tex @@ -0,0 +1,202 @@ +\chapter{Exercise 00} +\extitle{\$PATH} +\turnindir{ex00} +\exnumber{00} +\exfiles{answers.txt, requirements.txt} +\exforbidden{None} +\makeheaderfilesforbidden\\ +\emph{The first thing you need to do is to install Python.} +\\\\ +Most modern Unix-based systems have a \texttt{python} interpreter installed by default, +but its version might be lower/higher than the one used for these modules. +It is also possible that the default \texttt{python} command uses a version 2.x (for legacy reasons). +This is obviously very confusing for a new developper. +\\ + +\begin{42console} +$> python -V +$> python3 -V +\end{42console} +\hfill \break +To deal with those versions issues we will use \texttt{conda}. This program allows you to manage your Python packages and several working environments. +\\\\ +\emph{Note: the actual requirement is to use a Python 3.7.X version. You are free to use a different program/utilities to achieve this goal. At your own risk.} +\pagebreak + +% ===========================(Conda Manual) % +\section*{Conda manual installation} +\emph{Go to the next section for an automated installation.} +\\\\ +We recommend the following path for your \texttt{conda} folder. +\begin{42console} +$> MYPATH="/goinfre/$USER/miniconda3" +\end{42console} + +% ---------------------------------- % +\subsection*{1. Download \& Install conda} + +\begin{42console} +# For MAC +$> curl -LO "https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh" +$> sh Miniconda3-latest-MacOSX-x86_64.sh -b -p $MYPATH + +# For Linux +$> curl -LO "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh" +$> sh Miniconda3-latest-Linux-x86_64.sh -b -p $MYPATH +\end{42console} + + + +% ---------------------------------- % +\subsection*{2. Initial configuration of conda} +\begin{42console} +# For zsh +$> $MYPATH/bin/conda init zsh +$> $MYPATH/bin/conda config --set auto_activate_base false +$> source ~/.zshrc + +# For bash +$> $MYPATH/bin/conda init bash +$> $MYPATH/bin/conda config --set auto_activate_base false +$> source ~/.bash_profile +\end{42console} + + + +% ---------------------------------- % +\subsection*{3. Create a dedicated environment for 42AI !} +\begin{42console} +$> conda create --name 42AI-$USER python=3.7 jupyter pandas pycodestyle numpy +\end{42console} + + + +% ---------------------------------- % +\subsection*{4. Check your 42AI Python environment} +\begin{42console} +$> conda info --envs +$> conda activate 42AI-$USER +$> which python +$> python -V +$> python -c "print('Hello World!')" +\end{42console} + + + +% ---------------------------------- % +\subsection*{Help !} +\begin{itemize} + \item \textbf{I have lost my miniconda3 folder !} Repeat step 1 and 3. + \item \textbf{I have lost my home directory !} Repeat step 2. +\end{itemize} +\pagebreak + + + +% ===========================(Conda Auto) % +\section*{Conda automated installation} + +Copy the following script into a file, launch it and follow the instructions. It downloads and installs miniconda in a \texttt{/goinfre} subfolder and creates a \texttt{python} environment in \texttt{conda}. + + +\begin{42console} +#!/bin/bash + +function which_dl { + # If operating system name contains Darwnin: MacOS. Else Linux + if uname -s | grep -iqF Darwin; then + echo "Miniconda3-latest-MacOSX-x86_64.sh" + else + echo "Miniconda3-latest-Linux-x86_64.sh" + fi +} + +function which_shell { + # if $SHELL contains zsh, zsh. Else Bash + if echo $SHELL | grep -iqF zsh; then + echo "zsh" + else + echo "bash" + fi +} + +function when_conda_exist { + # check and install 42AI environement + printf "Checking 42AI-$USER environment: " + if conda info --envs | grep -iqF 42AI-$USER; then + printf "\e[33mDONE\e[0m\n" + else + printf "\e[31mKO\e[0m\n" + printf "\e[33mCreating 42AI environnment:\e[0m\n" + conda update -n base -c defaults conda -y + conda create --name 42AI-$USER python=3.7 jupyter numpy pandas pycodestyle -y + fi +} + +function set_conda { + MINICONDA_PATH="/goinfre/$USER/miniconda3" + CONDA=$MINICONDA_PATH"/bin/conda" + PYTHON_PATH=$(which python) + REQUIREMENTS="jupyter numpy pandas pycodestyle" + SCRIPT=$(which_dl) + MY_SHELL=$(which_shell) + DL_LINK="https://repo.anaconda.com/miniconda/"$SCRIPT + DL_LOCATION="/tmp/" + + printf "Checking conda: " + TEST=$(conda -h 2>/dev/null) + if [ $? == 0 ] ; then + printf "\e[32mOK\e[0m\n" + when_conda_exist + return + fi + printf "\e[31mKO\e[0m\n" + if [ ! -f $DL_LOCATION$SCRIPT ]; then + printf "\e[33mDonwloading installer:\e[0m\n" + cd $DL_LOCATION + curl -LO $DL_LINK + cd - + fi + printf "\e[33mInstalling conda:\e[0m\n" + sh $DL_LOCATION$SCRIPT -b -p $MINICONDA_PATH + printf "\e[33mConda initial setup:\e[0m\n" + $CONDA init $MY_SHELL + $CONDA config --set auto_activate_base false + + printf "\e[33mCreating 42AI-$USER environnment:\e[0m\n" + $CONDA update -n base -c defaults conda -y + $CONDA create --name 42AI-$USER python=3.7 jupyter numpy pandas pycodestyle -y + printf "\e[33mLaunch the following command or restart your shell:\e[0m\n" + if [ $MY_SHELL == "zsh" ]; then + printf "\tsource ~/.zshrc\n" + else + printf "\tsource ~/.bash_profile\n" + fi +} + +set_conda +\end{42console} +\hfill \break +Don't forget to check your 42AI Python environment ! +\begin{42console} +conda info --envs +conda activate 42AI-$USER +which python +python -V +python -c "print('Hello World!')" +\end{42console} + +% =================================(Question) % +\section*{(Finally) getting started} + +Now that your setup is ready to run, here are a few questions that need to be solved using \texttt{python}, \texttt{pip} or \texttt{conda}. Save your answers in a file \texttt{answers.txt} (one answer per line and per question), and check them with your peers.\\\\ +Find the commands to: +\begin{itemize} + \item Output a list of installed packages and their versions. + \item Show the package metadata of \texttt{numpy}. + \item Remove the package \texttt{numpy}. + \item (Re)install the package \texttt{numpy}. + \item Freeze your \texttt{python} packages and their versions in a \texttt{requirements.txt} file you have to turn-in. +\end{itemize} + + diff --git a/module00/subject/exercises/m00ex01.tex b/module00/subject/exercises/m00ex01.tex new file mode 100644 index 00000000..a0836e06 --- /dev/null +++ b/module00/subject/exercises/m00ex01.tex @@ -0,0 +1,27 @@ +\chapter{Exercise 01} +\extitle{Rev Alpha} +\turnindir{ex01} +\exnumber{01} +\exfiles{exec.py} +\exforbidden{None} +\makeheaderfilesforbidden +\newline +Make a program that takes a string as argument, reverses it, swaps its letters case and prints the result. + +\begin{itemize} + \item If more than one argument is provided, merge them into a single string with each argument separated by a single space character. + \item If no argument is provided, do nothing or print an usage. +\end{itemize} +% --------------------------------- % +\section*{Examples} + +\begin{42console} +$> python3 exec.py 'Hello World!' | cat -e +!DLROw OLLEh$ +$> +$> python3 exec.py 'Hello' 'my Friend' | cat -e +DNEIRf YM OLLEh$ +$> +$> python3 exec.py +$> +\end{42console} diff --git a/module00/subject/exercises/m00ex02.tex b/module00/subject/exercises/m00ex02.tex new file mode 100644 index 00000000..94fe7481 --- /dev/null +++ b/module00/subject/exercises/m00ex02.tex @@ -0,0 +1,38 @@ +\chapter{Exercise 02} +\extitle{The Odd, the Even and the Zero} +\turnindir{ex02} +\exnumber{02} +\exfiles{whois.py} +\exforbidden{None} +\makeheaderfilesforbidden +Make a program that takes a number as argument, checks whether it is odd, even or zero, and prints the result. +\begin{itemize} + \item If more than one argument is provided or if the argument is not an integer, print an error message. + \item If no argument is provided, do nothing or print an usage. +\end{itemize} + +% --------------------------------- % +\section*{Examples} +\begin{42console} +$> python3 whois.py 12 +I'm Even. +$> +$> python3 whois.py 3 +I'm Odd. +$> +$> python3 whois.py +$> +$> python3 whois.py 0 +I'm Zero. +$> +$> python3 whois.py Hello +AssertionError: argument is not an integer +$> +$> python3 whois.py 12 3 +AssertionError: more than one argument is provided +$> +\end{42console} + +\hint{ + No bonus point to be gained from a complex error management system. Keep it simple. +} diff --git a/module00/subject/exercises/m00ex03.tex b/module00/subject/exercises/m00ex03.tex new file mode 100644 index 00000000..af0766d1 --- /dev/null +++ b/module00/subject/exercises/m00ex03.tex @@ -0,0 +1,89 @@ +\chapter{Exercise 03} +\extitle{Functional file} +\turnindir{ex03} +\exnumber{03} +\exfiles{count.py} +\exforbidden{None} +\makeheaderfilesforbidden +\section*{Part 1. text\_analyzer} +Create a function called \texttt{text\_analyzer} that takes a single string argument +and displays the total number of printable characters, and respectively : the number of upper-case characters, lower-case characters, punctuation characters and spaces. +\begin{itemize} + \item If \texttt{None} or nothing is provided, the user is prompted to provide a string. + \item If the argument is not a string, print an error message. + \item This function must have a \texttt{docstring} explaning its behavior. +\end{itemize} +Test your function within the \texttt{python} console + +% --------------------------------- % +\subsection*{Examples} +\begin{42console} +$> python3 +>>> from count import text_analyzer +>>> text_analyzer("Python 2.0, released 2000, introduced +features like List comprehensions and a garbage collection +system capable of collecting reference cycles.") +The text contains 143 printable character(s): +- 2 upper letter(s) +- 113 lower letter(s) +- 4 punctuation mark(s) +- 18 space(s) +>>> text_analyzer("Python is an interpreted, high-level, +general-purpose programming language. Created by Guido van +Rossum and first released in 1991, Python's design philosophy +emphasizes code readability with its notable use of significant +whitespace.") +The text contains 234 printable character(s): +- 5 upper letter(s) +- 187 lower letter(s) +- 8 punctuation mark(s) +- 30 space(s) +>>> text_analyzer() +What is the text to analyze? +>> Hello World! +The text contains 12 printable character(s): +- 2 upper letter(s) +- 8 lower letter(s) +- 1 punctuation mark(s) +- 1 space(s) +>>> text_analyzer(42) +AssertionError: argument is not a string +>>> print(text_analyzer.__doc__) + + This function counts the number of upper characters, lower characters, + punctuation and spaces in a given text. +\end{42console} + +\hint{ + Python has a lot of very convenient built-in functions and methods. Do some research, you do not have to reivent the wheel ! +} + +% ================================= % +\section*{Part 2. \_\_name\_\_==\_\_main\_\_} + +In the previous part, you wrote a function that can be used in the console or in another file when imported. +Without changing this behavior, update your file so it can also be launched as a standalone program. + +\begin{itemize} + \item If more than one argument is provided to the program, print an error message. + \item Otherwise, use the \texttt{text\_analyzer} function. +\end{itemize} + +% --------------------------------- % +\subsection*{Examples} +\begin{42console} +$> python3 count.py 'Hello World!' +The text contains 12 character(s): +- 2 upper letter(s) +- 8 lower letter(s) +- 1 punctuation mark(s) +- 1 space(s) +$> python3 +>>> from count import text_analyzer +>>> text_analyzer("Hello World!") +The text contains 12 character(s): +- 2 upper letter(s) +- 8 lower letter(s) +- 1 punctuation mark(s) +- 1 space(s) +\end{42console} \ No newline at end of file diff --git a/module00/subject/exercises/m00ex04.tex b/module00/subject/exercises/m00ex04.tex new file mode 100644 index 00000000..aeac1fd1 --- /dev/null +++ b/module00/subject/exercises/m00ex04.tex @@ -0,0 +1,63 @@ +\chapter{Exercise 04} +\extitle{Elementary} +\turnindir{ex04} +\exnumber{04} +\exfiles{operations.py} +\exforbidden{None} +\makeheaderfilesforbidden\\ +Write a program that takes two integers A and B as arguments and prints the result of the following operations: +\newline +\begin{42console} +Sum: A+B +Difference: A-B +Product: A*B +Quotient: A/B +Remainder: A%B +\end{42console} + +\begin{itemize} + \item If more or less than two arguments are provided or if one of the arguments is not an integer, print an error message. + \item If no argument is provided, do nothing or print an usage. + \item If an operation is impossible, print an error message instead of a numerical result. +\end{itemize} + +% ================================= % +\section*{Examples} +\begin{42console} +$> python3 operations.py 10 3 +Sum: 13 +Difference: 7 +Product: 30 +Quotient: 3.3333... +Remainder: 1 +$> +$> python3 operations.py 42 10 +Sum: 52 +Difference: 32 +Product: 420 +Quotient: 4.2 +Remainder: 2 +$> +$> python3 operations.py 1 0 +Sum: 1 +Difference: 1 +Product: 0 +Quotient: ERROR (division by zero) +Remainder: ERROR (modulo by zero) +$> +$> python3 operations.py +Usage: python operations.py +Example: + python operations.py 10 3 +$> +$> python3 operations.py 12 10 5 +AssertionError: too many arguments +$> +$> python3 operations.py "one" "two" +AssertionError: only integers +$> +\end{42console} + +\hint{ + No bonus point to be gained from handling decimal point or scientific notation. Keep it simple. +} \ No newline at end of file diff --git a/module00/subject/exercises/m00ex05.tex b/module00/subject/exercises/m00ex05.tex new file mode 100644 index 00000000..54a0d7e6 --- /dev/null +++ b/module00/subject/exercises/m00ex05.tex @@ -0,0 +1,109 @@ +\chapter{Exercise 05} +\extitle{The right format} +\turnindir{ex05} +\exnumber{05} +\exfiles{kata00.py, kata01.py, kata02.py, kata03.py, kata04.py} +\exforbidden{None} +\makeheaderfilesforbidden +Let's get familiar with the useful concept of \textbf{string formatting} through a kata series.\\ +\newline +Each exercice will provide you with a \texttt{kata} variable. This variable can be modified to a certain extent: your program must react accordingly. +% ================================= % +\section*{kata00} +The \texttt{kata} variable is always a tuple and can only be filled with integers. +\begin{42console} +# Put this at the top of your kata00.py file +kata = (19,42,21) +\end{42console} +Write a program that displays this variable content according to the format shown below: + +\begin{42console} +$> python3 kata00.py +The 3 numbers are: 19, 42, 21 +$> +\end{42console} + +% ================================= % +\section*{kata01} + +The \texttt{kata} variable is always a dictionary and can only be filled with strings. + +\begin{42console} +# Put this at the top of your kata01.py file +kata = { + 'Python': 'Guido van Rossum', + 'Ruby': 'Yukihiro Matsumoto', + 'PHP': 'Rasmus Lerdorf', + } +\end{42console} +Write a program that displays this variable content according to the format shown below: + +\begin{42console} +$> python3 kata01.py +Python was created by Guido van Rossum +Ruby was created by Yukihiro Matsumoto +PHP was created by Rasmus Lerdorf +$> +\end{42console} + +% ================================= % +\section*{kata02} + +The \texttt{kata} variable is always a tuple that contains 5 non-negative integers. The first integer contains up to 4 digits, the rest up to 2 digits. + +\begin{42console} +# Put this at the top of your kata02.py file +kata = (2019, 9, 25, 3, 30) +\end{42console} +Write a program that displays this variable content according to the format shown below: + +\begin{42console} +$> python3 kata02.py | cat -e +09/25/2019 03:30$ +$> python3 kata02.py | wc -c +17 +$> +\end{42console} + +% ================================= % +\section*{kata03} + +The \texttt{kata} variable is always a string whose length is not higher than 42. + +\begin{42console} +# Put this at the top of your kata03.py file +kata = "The right format" +\end{42console} +Write a program that displays this variable content according to the format shown below: + +\begin{42console} +$> python3 kata03.py | cat -e +--------------------------The right format% +$> python3 kata03.py | wc -c +42 +$> +\end{42console} + +% ================================= % +\section*{kata04} + +The \texttt{kata} variable is always a tuple that contains, in the following order: +\begin{itemize} + \item 2 non-negative integers containing up to 2 digits + \item 1 decimal + \item 1 integer + \item 1 decimal +\end{itemize} + +\begin{42console} +# Put this at the top of your kata04.py file +kata = (0, 4, 132.42222, 10000, 12345.67) +\end{42console} +Write a program that displays this variable content according to the format shown below: + +\begin{42console} +$> python3 kata04.py +module_00, ex_04 : 132.42, 1.00e+04, 1.23e+04 +$> python3 kata04.py | cut -c 10,18 +,: +\end{42console} \ No newline at end of file diff --git a/module00/subject/exercises/m00ex06.tex b/module00/subject/exercises/m00ex06.tex new file mode 100644 index 00000000..6fe4d0ed --- /dev/null +++ b/module00/subject/exercises/m00ex06.tex @@ -0,0 +1,108 @@ +\chapter{Exercise 06} +\extitle{A recipe} +\turnindir{ex06} +\exnumber{06} +\exfiles{recipe.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Part 1: Nested Dictionaries} + +Create a dictionary called \texttt{cookbook}. You will use this \texttt{cookbook} to store recipes. +\\\\ +A recipe is a \textbf{dictionary} that stores (at least) 3 key-value pairs: +\begin{itemize} + \item ''ingredients": a \textbf{list of strings} containing the list of ingredients + \item "meal": a \textbf{string} representing the type of meal + \item "prep\_time": a \textbf{non-negative integer} representing a preparation time in minutes +\end{itemize} +In the \texttt{cookbook}, the \textbf{key} to a recipe is the recipe's name. +\\ +Initialize your \texttt{cookbook} with 3 recipes: +\begin{itemize} + \item The Sandwich's ingredients are \textit{ham}, \textit{bread}, \textit{cheese} and \textit{tomatoes}. +It is a \textit{lunch} and it takes $10$ minutes of preparation. + \item The Cake's ingredients are \textit{flour}, \textit{sugar} and \textit{eggs}. +It is a \textit{dessert} and it takes $60$ minutes of preparation. + \item The Salad's ingredients are \textit{avocado}, \textit{arugula}, \textit{tomatoes} and \textit{spinach}. +It is a \textit{lunch} and it takes $15$ minutes of preparation. +\end{itemize} + +% ================================= % +\newpage +\section*{Part 2: A Handful of Helpful Functions} + +Create a series of useful functions to handle your \texttt{cookbook}: + +\begin{enumerate} + \item A function that prints all recipe names. + \item A function that takes a recipe name and prints its details. + \item A function that takes a recipe name and delete it. + \item A function that adds a recipe from user input. You will need a name, a list of ingredients, a meal type and a preparation time. +\end{enumerate} +\subsection*{Input example} +\begin{42console} +>>> Enter a name: +chips +>>> Enter ingredients: +potatoes +oil +salt + +>>> Enter a meal type: +lunch +>>> Enter a preparation time: +15 +\end{42console} + +% ================================= % +\section*{Part 3: A command line executable !} + +Create a program that uses your \texttt{cookbook} and your functions.\\ +\newline +The program will prompt the user to make a choice between printing the cookbook's content, + printing one recipe, adding a recipe, deleting a recipe or quitting the cookbook.\\ +\newline +Your program will continue to prompt the user until the user decides to quit it.\\ +\newline +The program cannot crash if a wrong value is entered: you must handle the error and ask for another prompt.\\ + +\begin{42console} +$> python3 recipe.py +Welcome to the Python Cookbook ! +List of available options: + 1: Add a recipe + 2: Delete a recipe + 3: Print a recipe + 4: Print the cookbook + 5: Quit + +Please select an option: +>> 3 + +Please enter a recipe name to get its details: +>> cake + +Recipe for cake: + Ingredients list: ['flour', 'sugar', 'eggs'] + To be eaten for dessert. + Takes 60 minutes of cooking. + +Please select an option: +>> Hello + +Sorry, this option does not exist. +List of available options: + 1: Add a recipe + 2: Delete a recipe + 3: Print a recipe + 4: Print the cookbook + 5: Quit + +Please select an option: +>> 5 + +Cookbook closed. Goodbye ! +$> +\end{42console} \ No newline at end of file diff --git a/module00/subject/exercises/m00ex07.tex b/module00/subject/exercises/m00ex07.tex new file mode 100644 index 00000000..857af2dd --- /dev/null +++ b/module00/subject/exercises/m00ex07.tex @@ -0,0 +1,32 @@ +\chapter{Exercise 07} +\extitle{Shorter, Faster ... Pythonic !} +\turnindir{ex07} +\exnumber{07} +\exfiles{filterwords.py} +\exforbidden{filter} +\makeheaderfilesforbidden +Make a program that takes a string S and an integer N as argument and prints the list of words in S that contains more than N non-punctuation characters. + +\begin{itemize} + \item Words are separated from each other by space characters + \item Punctuation symbols must be removed from the printed list: they are neither part of a word nor a separator + \item The program must contain at least one \textbf{list comprehension} expression. +\end{itemize} +If the number of argument is different from 2, or if the type of any argument is invalid, the program prints an error message. + +\section*{Examples} +\begin{42console} +$> python3 filterwords.py 'Hello, my friend' 3 +['Hello', 'friend'] +$> python3 filterwords.py 'Hello, my friend' 10 +[] +$> python3 filterwords.py 'A robot must protect its own existence as long as such protection does not conflict with the First or Second Law' 6 +['protect', 'existence', 'protection', 'conflict'] +$> python3 filterwords.py Hello World +ERROR +$> python3 filterwords.py 3 'Hello, my friend' +ERROR +$> python3 filterwords.py +ERROR +\end{42console} + \ No newline at end of file diff --git a/module00/subject/exercises/m00ex08.tex b/module00/subject/exercises/m00ex08.tex new file mode 100644 index 00000000..903231ec --- /dev/null +++ b/module00/subject/exercises/m00ex08.tex @@ -0,0 +1,34 @@ +\chapter{Exercise 08} +\extitle{S.O.S} +\turnindir{ex08} +\exnumber{08} +\exfiles{sos.py} +\exforbidden{None} +\makeheaderfilesforbidden +Make a program that takes a string as argument and encodes it into Morse code. +\begin{itemize} + \item The program supports space and alphanumeric characters + \item An alphanumeric character is represented by dots \texttt{.} and dashes \texttt{-} + \item A space character is represented by a slash \texttt{/} + \item Complete morse characters are separated by a single space\\ +\end{itemize} +If more than one argument is provided, merge them into a single string with each argument separated by a single space character.\\ +\newline +If no argument is provided, do nothing or print an usage. + +% ================================= % +\section*{Examples} +\begin{42console} + $> python3 sos.py "SOS" + ... --- ... + $> python3 sos.py + $> python3 sos.py "HELLO / WORLD" + ERROR + + $> python3 sos.py "96 BOULEVARD" "Bessiere" + ----. -.... / -... --- ..- .-.. . ...- .- .-. -.. / -... . ... ... .. . .-. . +\end{42console} + +\hint{ + \url{https://morsecode.world/international/morse2.html} +} \ No newline at end of file diff --git a/module00/subject/exercises/m00ex09.aux b/module00/subject/exercises/m00ex09.aux new file mode 100644 index 00000000..0eb3231d --- /dev/null +++ b/module00/subject/exercises/m00ex09.aux @@ -0,0 +1,43 @@ +\relax +\providecommand\zref@newlabel[2]{} +\providecommand\hyper@newdestlabel[2]{} +\@writefile{toc}{\contentsline {chapter}{\numberline {XI}Exercise 09}{20}{chapter.11}\protected@file@percent } +\@writefile{lof}{\addvspace {10\p@ }} +\@writefile{lot}{\addvspace {10\p@ }} +\@setckpt{exercises/m00ex09}{ +\setcounter{page}{22} +\setcounter{equation}{0} +\setcounter{enumi}{4} +\setcounter{enumii}{0} +\setcounter{enumiii}{0} +\setcounter{enumiv}{0} +\setcounter{footnote}{0} +\setcounter{mpfootnote}{0} +\setcounter{part}{0} +\setcounter{chapter}{11} +\setcounter{section}{0} +\setcounter{subsection}{0} +\setcounter{subsubsection}{0} +\setcounter{paragraph}{0} +\setcounter{subparagraph}{0} +\setcounter{figure}{0} +\setcounter{table}{0} +\setcounter{lstnumber}{10} +\setcounter{section@level}{0} +\setcounter{Item}{4} +\setcounter{Hfootnote}{0} +\setcounter{bookmark@seq@number}{11} +\setcounter{float@type}{16} +\setcounter{lofdepth}{1} +\setcounter{lotdepth}{1} +\setcounter{FancyVerbLine}{0} +\setcounter{listing}{0} +\setcounter{mdf@globalstyle@cnt}{0} +\setcounter{mdfcountframes}{0} +\setcounter{mdf@env@i}{0} +\setcounter{mdf@env@ii}{0} +\setcounter{mdf@zref@counter}{0} +\setcounter{exerciceCounter}{12} +\setcounter{itemizeCounter}{0} +\setcounter{lstlisting}{0} +} diff --git a/module00/subject/exercises/m00ex09.tex b/module00/subject/exercises/m00ex09.tex new file mode 100644 index 00000000..8080ca69 --- /dev/null +++ b/module00/subject/exercises/m00ex09.tex @@ -0,0 +1,73 @@ +\chapter{Exercise 09} +\extitle{Secret number} +\turnindir{ex09} +\exnumber{09} +\exfiles{guess.py} +\exforbidden{None} +\makeheaderfilesforbidden +You have to make a program that will be an interactive guessing game.\\ +\newline +It will prompt the user to guess a number between $1$ and $99$. The program will tell the user if their +input is too high or too low. +\newline +The game ends when the user finds out the secret number or types \texttt{exit}.\\ +\newline +You will import the \texttt{random} module with the \texttt{randint} function to get a random number. +You have to count the number of trials and print that number when the user wins. + +\section*{Examples} +\begin{42console} +$> python guess.py +This is an interactive guessing game! +You have to enter a number between 1 and 99 to find out the secret number. +Type 'exit' to end the game. +Good luck! + +What's your guess between 1 and 99? +>> 54 +Too high! +What's your guess between 1 and 99? +>> 34 +Too low! +What's your guess between 1 and 99? +>> 45 +Too high! +What's your guess between 1 and 99? +>> A +That's not a number. +What's your guess between 1 and 99? +>> 43 +Congratulations, you've got it! +You won in 5 attempts! +\end{42console} +If the user discovers the secret number on the first try, tell them !\\ +\newline +If the secret number is 42, make a reference to Douglas Adams.\\ +\newline + +\begin{42console} + $> python guess.py + This is an interactive guessing game! + You have to enter a number between 1 and 99 to find out the secret number. + Type 'exit' to end the game. + Good luck! + + What's your guess between 1 and 99? + >> 42 + The answer to the ultimate question of life, the universe and everything is 42. + Congratulations! You got it on your first try! +\end{42console} + +Other example: + +\begin{42console} + $> python guess.py + This is an interactive guessing game! + You have to enter a number between 1 and 99 to find out the secret number. + Type 'exit' to end the game. + Good luck! + + What's your guess between 1 and 99? + >> exit + Goodbye! +\end{42console} diff --git a/module00/subject/exercises/m00ex10.aux b/module00/subject/exercises/m00ex10.aux new file mode 100644 index 00000000..87f6dc37 --- /dev/null +++ b/module00/subject/exercises/m00ex10.aux @@ -0,0 +1,43 @@ +\relax +\providecommand\zref@newlabel[2]{} +\providecommand\hyper@newdestlabel[2]{} +\@writefile{toc}{\contentsline {chapter}{\numberline {XII}Exercise 10}{22}{chapter.12}\protected@file@percent } +\@writefile{lof}{\addvspace {10\p@ }} +\@writefile{lot}{\addvspace {10\p@ }} +\@setckpt{exercises/m00ex10}{ +\setcounter{page}{24} +\setcounter{equation}{0} +\setcounter{enumi}{4} +\setcounter{enumii}{0} +\setcounter{enumiii}{0} +\setcounter{enumiv}{0} +\setcounter{footnote}{0} +\setcounter{mpfootnote}{0} +\setcounter{part}{0} +\setcounter{chapter}{12} +\setcounter{section}{0} +\setcounter{subsection}{0} +\setcounter{subsubsection}{0} +\setcounter{paragraph}{0} +\setcounter{subparagraph}{0} +\setcounter{figure}{0} +\setcounter{table}{0} +\setcounter{lstnumber}{5} +\setcounter{section@level}{0} +\setcounter{Item}{4} +\setcounter{Hfootnote}{0} +\setcounter{bookmark@seq@number}{12} +\setcounter{float@type}{16} +\setcounter{lofdepth}{1} +\setcounter{lotdepth}{1} +\setcounter{FancyVerbLine}{0} +\setcounter{listing}{0} +\setcounter{mdf@globalstyle@cnt}{0} +\setcounter{mdfcountframes}{0} +\setcounter{mdf@env@i}{0} +\setcounter{mdf@env@ii}{0} +\setcounter{mdf@zref@counter}{0} +\setcounter{exerciceCounter}{12} +\setcounter{itemizeCounter}{0} +\setcounter{lstlisting}{0} +} diff --git a/module00/subject/exercises/m00ex10.tex b/module00/subject/exercises/m00ex10.tex new file mode 100644 index 00000000..cb206f06 --- /dev/null +++ b/module00/subject/exercises/m00ex10.tex @@ -0,0 +1,49 @@ +\chapter{Exercise 10} +\extitle{Loading bar!} +\turnindir{ex10} +\exnumber{10} +\exfiles{loading.py} +\exforbidden{\texttt{tqdm} or any library for automatic loading bar} +\makeheaderfilesforbidden +You are about to discover the \texttt{yield} operator!\\ +\newline +So let's create a function called \texttt{ft\_progress(lst)}.\\ +\newline +The function will display the progress of a \texttt{for} loop.\\ +\info{We strongly advise you to take a look at the wonderful \textbf{tqdm} library, it will come in handy in many situations !} +\section*{Examples} +\begin{42console}% SERAIT MIEUX AVEC UN ENVIRONNEMENT PYTHON + listy = range(1000) + ret = 0 + for elem in ft_progress(listy): + ret += (elem + 3) % 5 + sleep(0.01) + print() + print(ret) +\end{42console} + +\begin{42console} + $> python loading.py + ETA: 8.67s [ 23%][=====> ] 233/1000 | elapsed time 2.33s + ... + 2000 +\end{42console} +\newpage +\begin{42console}% SERAIT MIEUX AVEC UN ENVIRONNEMENT PYTHON + listy = range(3333) + ret = 0 + for elem in ft_progress(listy): + ret += elem + sleep(0.005) + print() + print(ret) +\end{42console} + +\begin{42console} + $> python loading.py + ETA: 14.67s [ 9%][=> ] 327/3333 | elapsed time 1.33s + ... + 5552778 +\end{42console} + + diff --git a/module01/exercises/m01ex00.tex b/module01/exercises/m01ex00.tex new file mode 100644 index 00000000..aefeb823 --- /dev/null +++ b/module01/exercises/m01ex00.tex @@ -0,0 +1,87 @@ +\chapter{Exercise 00} +\extitle{The Book} +\turnindir{ex00} +\exnumber{00} +\exfiles{book.py, recipe.py, test.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================== % +\section*{Objective} +% ---------------------------------- % +The goal of this exercise is to get you familiar with the notions of +classes and the manipulation of the objects related to these classes. + +% ================================== % +\section*{Instructions} +% ---------------------------------- % +You will have to make a class \texttt{Book} and a class \texttt{Recipe}. +The classes \texttt{Book} and \texttt{Recipe} will be written in +\texttt{book.py} and \texttt{recipe.py} respectively.\\ +\newline +Let's describe the \texttt{Recipe} class. It has some attributes: +\begin{itemize} + \item \texttt{name} (str): name of the recipe, + \item \texttt{cooking\_lvl} (int): range from $1$ to $5$, + \item \texttt{cooking\_time} (int): in minutes (no negative numbers), + \item \texttt{ingredients} (list): list of all ingredients each represented by a string, + \item \texttt{description} (str): description of the recipe, + \item \texttt{recipe\_type} (str): can be "starter", "lunch" or "dessert". +\end{itemize} +You have to \textbf{initialize} the object \texttt{Recipe} and check all of its values. Only the description can be empty. +In case of input errors, you should print what they are and exit properly.\\ +\newline +You will have to implement the built-in method \texttt{\_\_str\_\_}. +It's the method called when the following code is executed:\\ +\newline +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +tourte = Recipe(...) +to_print = str(tourte) +print(to_print) +\end{minted} +\newline +\newline +It is implemented this way:\\ +\newline +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +def __str__(self): + """Returns the string to print with the recipe's info""" + txt = "" + """Your code here""" + return txt +\end{minted} +\newline +The \texttt{Book} class also has some attributes: +\begin{itemize} + \item \texttt{name} (str): name of the book, + \item \texttt{last\_update} \href{https://docs.python.org/3/library/datetime.html}{(datetime)}: the date of the last update, + \item \texttt{creation\_date} \href{https://docs.python.org/3/library/datetime.html}{(datetime)}: the creation date of the book, + \item \texttt{recipes\_list} (dict): a dictionnary with 3 keys: "starter", "lunch", "dessert". +\end{itemize} +You will have to implement some methods in the \texttt{Book} class:\\ +\newline +\begin{minted}[bgcolor=darcula-back ,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +def get_recipe_by_name(self, name): + """Prints a recipe with the name \texttt{name} and returns the instance""" + #... Your code here ... + +def get_recipes_by_types(self, recipe_type): + """Gets all recipes names for a given recipe_type """ + #... Your code here ... + +def add_recipe(self, recipe): + """Adds a recipe to the book and updates last_update""" + #... Your code here ... +\end{minted} +\newline +You have to handle the error if the argument passed in \texttt{add\_recipe} is not a \texttt{Recipe}.\\ +\newline +Finally, you will provide a \texttt{test.py} file to test your classes and prove that they are working properly. +You can import all the classes into your \texttt{test.py} file by adding these lines at the top of the \texttt{test.py} file:\\ +\newline +\begin{minted}[bgcolor=darcula-back ,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from book import Book +from recipe import Recipe + +# ... Your tests ... +\end{minted} \ No newline at end of file diff --git a/module01/exercises/m01ex01.tex b/module01/exercises/m01ex01.tex new file mode 100644 index 00000000..ba50f1d3 --- /dev/null +++ b/module01/exercises/m01ex01.tex @@ -0,0 +1,76 @@ +\chapter{Exercise 01} +\extitle{Family tree} +\turnindir{ex01} +\exnumber{01} +\exfiles{game.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of the exercise is to tackle the notion of class inheritance. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +Create a \texttt{GotCharacter} class and initialize it with the following attributes: +\begin{itemize} + \item \texttt{first\_name}, + \item \texttt{is\_alive} (by default is \texttt{True}). +\end{itemize} +Pick up a Game of Thrones House (e.g., Stark, Lannister...), create a child class that inherits from \texttt{GotCharacter} and +define the following attributes: +\begin{itemize} + \item \texttt{family\_name} (by default should be the same as the Class) + \item \texttt{house\_words} (e.g., the House words for the Stark House is: "Winter is Coming")\\ +\end{itemize} +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + class Stark(GotCharacter): + def __init__(self, first_name=None, is_alive=True): + super().__init__(first_name=first_name, is_alive=is_alive) + self.family_name = "Stark" + self.house_words = "Winter is Coming" +\end{minted} + +\newpage +Add two methods to your child class: +\begin{itemize} + \item \texttt{print\_house\_words}: prints the House words, + \item \texttt{die}: changes the value of \texttt{is\_alive} to \texttt{False}. +\end{itemize} + +\section*{Examples} +Running commands in the Python console, an example of what you should get:\\ +\newline + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + $> python + >>> from game import Stark + + >>> arya = Stark("Arya") + >>> print(arya.__dict__) + {'first_name': 'Arya', 'is_alive': True, 'family_name': 'Stark', 'house_words': 'Winter is Coming'} + + >>> arya.print_house_words() + Winter is Coming + + >>> print(arya.is_alive) + True + + >>> arya.die() + >>> print(arya.is_alive) + False +\end{minted} +\newline +You can add any attribute or method you need to your class and format the docstring the way you want. +Feel free to create other children of \texttt{GotCharacter} class. +\newline +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + $> python + >>> from game import Stark + + >>> arya = Stark("Arya") + >>> print(arya.__doc__) + A class representing the Stark family. Or when bad things happen to good people. +\end{minted} \ No newline at end of file diff --git a/module01/exercises/m01ex02.tex b/module01/exercises/m01ex02.tex new file mode 100644 index 00000000..4aa91a23 --- /dev/null +++ b/module01/exercises/m01ex02.tex @@ -0,0 +1,239 @@ +\chapter{Exercise 02} +\extitle{The Vector} +\turnindir{ex02} +\exnumber{02} +\exfiles{vector.py, test.py} +\exforbidden{Numpy library} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to get you used to working with built-in methods, more +particularly with those allowing to perform operations. +You are expected to code built-in methods for vector-vector and +vector-scalar operations as rigorously as possible. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +In this exercise, you have to create a \texttt{Vector} class. The goal is to +create vectors and be able to perform mathematical operations with them. +\begin{itemize} + \item Column vectors are represented as list of lists of single float (\texttt{[[1.], [2.], [3.]]}), + \item Row vectors are represented as a list of a list of several floats (\texttt{[[1., 2., 3.]]}). +\end{itemize} + +\warn{A vector is either a single line of floats or a single column of floats. When more than a line/column is considered, it is a matrix, not a vector.} + + +The class should also have 2 attributes: +\begin{itemize} + \item \texttt{values}: list of list of floats (for row vector) or list of lists of single float (for column vector), + \item \texttt{shape}: tuple of 2 integers: \texttt{(1,n)} for a row vector of dimension $n$ + or \texttt{(n,1)} for a column vector of dimension $n$. +\end{itemize} + +\info{If you did not learn at school what is the dimension of a vector, don't worry. +But for now do not think too hard about what dimension means. +Just consider the dimension is the number of floats (elements/coordinates) of a vector, and shape gives the layout: + if $(1, n)$ the vector is a row, if $(n,1)$ the vector is a column.} + +Finally you have to implement 2 methods: +\begin{itemize} + \item \texttt{.dot()} produces a dot product between two vectors of same \textbf{shape}, + \item \texttt{.T()} returns the transpose vector (i.e. a column vector into a row vector, or a row vector into a column vector). +\end{itemize} + +You will also provide a test file (\texttt{test.py}) to demonstrate your class +works as expected. In this test file, you will demonstrate: +\begin{itemize} + \item the addition and substraction are working for 2 vectors of the same shape, + \item the multiplication (\texttt{mul} and \texttt{rmul}) are working for a vector and a scalar, + \item the division (\texttt{truediv}) is working with a vector and a scalar, + \item the division (\texttt{rtruediv}) raises an Arithmetic Error (this test can be commented for the other tests and uncommented to show this one), +\end{itemize} + +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# Column vector of shape n * 1 +v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) +v2 = v1 * 5 +print(v2) +# Expected output: +# Vector([[0.0], [5.0], [10.0], [15.0]]) + +# Row vector of shape 1 * n +v1 = Vector([[0.0, 1.0, 2.0, 3.0]]) +v2 = v1 * 5 +print(v2) +# Expected output +# Vector([[0.0, 5.0, 10.0, 15.0]]) + +v2 = v1 / 2.0 +print(v2) +# Expected output +# Vector([[0.0, 0.5, 1.0, 1.5]]) + +v1 / 0.0 +# Expected ouput +# ZeroDivisionError: division by zero. + +2.0 / v1 +# Expected output: +# NotImplementedError: Division of a scalar by a Vector is not defined here. +\end{minted} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# Column vector of shape (n, 1) +print(Vector([[0.0], [1.0], [2.0], [3.0]]).shape) +# Expected output +# (4,1) + +print(Vector([[0.0], [1.0], [2.0], [3.0]]).values) +# Expected output +# [[0.0], [1.0], [2.0], [3.0]] + +# Row vector of shape (1, n) +print(Vector([[0.0, 1.0, 2.0, 3.0]]).shape) +# Expected output +# (1,4) + +print(Vector([[0.0, 1.0, 2.0, 3.0]]).values) +# Expected output +# [[0.0, 1.0, 2.0, 3.0]] +\end{minted} + + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# Example 1: +v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) +print(v1.shape) +# Expected output: +(4,1) + +print(v1.T()) +# Expected output: +# Vector([[0.0, 1.0, 2.0, 3.0]]) + +print(v1.T().shape) +# Expected output: +# (1,4) + +# Example 2: +v2 = Vector([[0.0, 1.0, 2.0, 3.0]]) +print(v2.shape) +# Expected output: +# (1,4) + +print(v2.T()) +# Expected output: +# Vector([[0.0], [1.0], [2.0], [3.0]]) + +print(v2.T().shape) +# Expected output: +# (4,1) +\end{minted} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + # Example 1: + v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) + v2 = Vector([[2.0], [1.5], [2.25], [4.0]]) + print(v1.dot(v2)) + # Expected output: + # 18.0 + + v3 = Vector([[1.0, 3.0]]) + v4 = Vector([[2.0, 4.0]]) + print(v3.dot(v4)) + # Expected output: + # 14.0 + + v1 + # Expected output: to see what __repr__() should do + # [[0.0, 1.0, 2.0, 3.0]] + + print(v1) + # Expected output: to see what __str__() should do + # [[0.0, 1.0, 2.0, 3.0]] +\end{minted} + +You should be able to initialize the object with: +\begin{itemize} + \item a list of a list of floats: \texttt{Vector([[0.0, 1.0, 2.0, 3.0]])}, + \item a list of lists of single float: \texttt{Vector([[0.0], [1.0], [2.0], [3.0]])}, + \item a size: \texttt{Vector(3)} -> the vector will have \texttt{values = [[0.0], [1.0], [2.0]]}, + \item a range: \texttt{Vector((10,16))} -> the vector will have \texttt{values = [[10.0], [11.0], [12.0], [13.0], [14.0], [15.0]]}. + in \texttt{Vector((a,b))}, if \texttt{a > b}, you must display accurate error message. +\end{itemize} + +\textit{By default, the vectors are generated as classical column vectors if initialized with a size or range.} + +To perform arithmetic operations for Vector-Vector or Scalar-Vector, you have to implement all the following built-in functions (called \texttt{magic/special methods}) for your \texttt{Vector} class: + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + __add__ + __radd__ + # add & radd : only vectors of the same shape. + __sub__ + __rsub__ + # sub & rsub: only vectors of the same shape. + __truediv__ + # truediv : only with scalars (to perform division of a Vector by a scalar). + __rtruediv__ + # rtruediv : raises an NotImplementedError with the message "Division of a scalar by a Vector is not defined here." + __mul__ + __rmul__ + # mul & rmul: only scalars (to perform multiplication of a Vector by a scalar). + __str__ + __repr__ + # must be identical, i.e we expect that print(vector) and vector within python interpretor to behave the same, see corresponding example section. +\end{minted} + +\info{ + So it might be a good idea to implement \texttt{values} and \texttt{shape} before built-in arithmetic functions. + For the case not specified (e.g vector * vector) you should raise \texttt{NotImplementedError}. +} + + +% ================================= % +\section*{Mathematic notions} +% --------------------------------- % +The authorized vector operations are: + +\begin{itemize} + \item Addition between two vectors of same dimension $m$ + \begin{equation*} + x + y = + \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} + + \begin{bmatrix} y_1 \\ \vdots \\ y_m\end{bmatrix} \\ + = \begin{bmatrix} x_1 + y_1 \\ \vdots \\ x_m + y_m \end{bmatrix} + \end{equation*} + \item Substraction between two vectors of same dimension $m$ + \begin{equation*} + x - y = + \begin{bmatrix} x_1 \\ \vdots \\ y_m\end{bmatrix} - + \begin{bmatrix} x_1 \\ \vdots \\ y_m\end{bmatrix} + = \begin{bmatrix} x_1 - y_1 \\ \vdots \\ x_m - y_m \end{bmatrix} + \end{equation*} + \item Multiplication and division between one vector $m$ and one scalar. + \begin{equation*} + \alpha x = \alpha \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} = + \begin{bmatrix} \alpha x_1 \\ \vdots \\ \alpha x_m \end{bmatrix} + \end{equation*} + \item Dot product between two vectors of same dimension $m$ + \begin{equation*} + x \cdot y = \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} + \cdot + \begin{bmatrix} y_1 \\ \vdots \\ y_m\end{bmatrix} = + \sum_{i = 1}^{m} x_i \cdot y_i = x_1 \cdot y_1 + \dots + x_m \cdot y_m + \end{equation*} +\end{itemize} + +Do not forget to handle all types of error properly! + + +% ===========================(fin ex 02) % +% ============================================== % + diff --git a/module01/exercises/m01ex03.tex b/module01/exercises/m01ex03.tex new file mode 100644 index 00000000..d6429dc0 --- /dev/null +++ b/module01/exercises/m01ex03.tex @@ -0,0 +1,99 @@ +\chapter{Exercise 03} +\extitle{Generator!} +\turnindir{ex03} +\exnumber{03} +\exfiles{generator.py} +\exauthorize{random.randint, random.choice} +\exforbidden{random.shuffle, random.sample} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to discover the concept of generator object in Python. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +Code a function called \texttt{generator} that takes a text as input (only printable characters), uses the string +parameter \texttt{sep} as a splitting parameter, and \texttt{yield}s the resulting substrings. + +The function can take an optional argument. +The options are: +\begin{itemize} + \item \texttt{shuffle}: shuffles the list of words, + \item \texttt{unique}: returns a list where each word appears only once, + \item \texttt{ordered}: sorts the words alphabetically. +\end{itemize} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + # function prototype + def generator(text, sep=" ", option=None): + ''' + Splits the text according to sep value and yields the substrings. + ''' +\end{minted} + +You can only call one option at a time. + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + >> text = "Le Lorem Ipsum est simplement du faux texte." + >> for word in generator(text, sep=" "): + ... print(word) + ... + Le + Lorem + Ipsum + est + simplement + du + faux + texte. + + >> for word in generator(text, sep=" ", option="shuffle"): + ... print(word) + ... + simplement + texte. + est + faux + Le + Lorem + Ipsum + du + + >> for word in generator(text, sep=" ", option="ordered"): + ... print(word) + ... + Ipsum + Le + Lorem + du + est + faux + simplement + texte. +\end{minted} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +>> text = "Lorem Ipsum Lorem Ipsum" +>> for word in generator(text, sep=" ", option="unique"): +... print(word) +... +Lorem +Ipsum +\end{minted} + +The function should return "ERROR" one time if the \texttt{text} argument is not a string, or if the \texttt{option} argument is not valid. + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +>> text = 1.0 +>> for word in generator(text, sep="."): +... print(word) +... +ERROR +\end{minted} \ No newline at end of file diff --git a/module01/exercises/m01ex04.tex b/module01/exercises/m01ex04.tex new file mode 100644 index 00000000..dd3f4ace --- /dev/null +++ b/module01/exercises/m01ex04.tex @@ -0,0 +1,49 @@ +\chapter{Exercise 04} +\extitle{Working with lists} +\turnindir{ex04} +\exnumber{04} +\exfiles{eval.py} +\exauthorize{zip and enumerate} +\exforbidden{while} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to discover 2 useful methods for lists, tuples, +dictionnaries (iterable class objects more generally) named \texttt{zip} +and \texttt{enumerate}. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +Code a class \texttt{Evaluator}, that has two static functions named \texttt{zip\_evaluate} +and \texttt{enumerate\_evaluate}. + + +The goal of these 2 functions is to compute the sum of the lengths of every +\texttt{words} of a given list weighted by a list of coefficients \texttt{coefs} (yes, the 2 functions should do the same thing). + +The lists \texttt{coefs} and \texttt{words} have to be of the same length. If this is not the +case, the function should return -1. + +You have to obtain the desired result using \texttt{zip} in the \texttt{zip\_evaluate} function, +and with \texttt{enumerate} in the \texttt{enumerate\_evaluate} function. + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +>> from eval import Evaluator +>> +>> words = ["Le", "Lorem", "Ipsum", "est", "simple"] +>> coefs = [1.0, 2.0, 1.0, 4.0, 0.5] +>> Evaluator.zip_evaluate(coefs, words) +32.0 +>> words = ["Le", "Lorem", "Ipsum", "n'", "est", "pas", "simple"] +>> coefs = [0.0, -1.0, 1.0, -12.0, 0.0, 42.42] +>> Evaluator.enumerate_evaluate(coefs, words) +-1 +\end{minted} + diff --git a/module01/exercises/m01ex05.tex b/module01/exercises/m01ex05.tex new file mode 100644 index 00000000..9715545b --- /dev/null +++ b/module01/exercises/m01ex05.tex @@ -0,0 +1,145 @@ +\chapter{Exercise 05} +\extitle{Bank Account} +\turnindir{ex05} +\exnumber{05} +\exfiles{the\_bank.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to discover new built-in functions, +deepen your class understanding, and to be aware of modifications on +instanced objects.\\ +In this exercise, you will learn how to modify or add attributes to an object. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +It is all about security. +Have a look at the class named \texttt{Account} in the code snippet below. + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# in the_bank.py +class Account(object): + + ID_COUNT = 1 + + def __init__(self, name, **kwargs): + self.__dict__.update(kwargs) + + self.id = self.ID_COUNT + Account.ID_COUNT += 1 + self.name = name + if not hasattr(self, 'value'): + self.value = 0 + + if self.value < 0: + raise AttributeError("Attribute value cannot be negative.") + if not isinstance(self.name, str) + raise AttributeError("Attribute name must be a str object.") + + def transfer(self, amount): + self.value += amount +\end{minted} + +Now, it is your turn to code a class named \texttt{Bank}! +Its purpose will be to handle the security part of each transfer attempt. + +Security means checking if the \texttt{Account} is: +\begin{itemize} + \item the right object, + \item not corrupted, + \item and stores enough money to complete the transfer. +\end{itemize} + +How do we define if a bank account is corrupted? A corrupted bank account has: +\begin{itemize} + \item an even number of attributes, + \item an attribute starting with \texttt{b}, + \item no attribute starting with \texttt{zip} or \texttt{addr}, + \item no attribute \texttt{name}, \texttt{id} and \texttt{value}, + \item \texttt{name} not being a string, + \item \texttt{id} not being an \texttt{int}, + \item \texttt{value} not being an \texttt{int} or a \texttt{float}. +\end{itemize} + +For the rest of the attributes (\texttt{addr}, \texttt{zip}, etc ... +there is no specific check expected. +Meaning you are not expected to evaluate the validity of the account based on the type of the other attributes (the conditions listed above are sufficient). + +Moreover, verification has to be performed when account objects are added to to Bank instance +(\texttt{bank.add(Account(...))}). +The verification in \texttt{add} only checsk the type of the new\_account and if there +is no account among the ones already in Bank instance with the same name. + +A transaction is invalid if \texttt{amount < 0} or if the amount is larger than +the balance of the account. +Prior to the transfer, the validity of the 2 accounts (\texttt{origin} and \texttt{dest}) are checked +(according to the list of criteria above). +A transfer between the same account (\texttt{bank.transfer('Wiliam John', 'William John')}) +is valid but there is no fund movement. + +\texttt{fix\_account} recovers a corrupted account if it parameter \texttt{name} correspond to the attribute +name of one of the account in \texttt{accounts} (attribute of Bank). If name is not a string or does not corresponded +to an account name, the method return \texttt{False}. + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# in the_bank.py +class Bank(object): + """The bank""" + def __init__(self): + self.accounts = [] + + def add(self, new_account): + """ Add new_account in the Bank + @new_account: Account() new account to append + @return True if success, False if an error occured + """ + # test if new_account is an Account() instance and if + # it can be appended to the attribute accounts + + # ... Your code ... + + self.accounts.append(new_account) + + def transfer(self, origin, dest, amount): + """" Perform the fund transfer + @origin: str(name) of the first account + @dest: str(name) of the destination account + @amount: float(amount) amount to transfer + @return True if success, False if an error occured + """ + # ... Your code ... + + def fix_account(self, name): + """ fix account associated to name if corrupted + @name: str(name) of the account + @return True if success, False if an error occured + """ + # ... Your code ... +\end{minted} + +Check out the \texttt{dir} built-in function. + +\warn{YOU WILL HAVE TO MODIFY THE INSTANCES' ATTRIBUTES IN ORDER TO FIX THEM.} + +% ================================= % +\section*{Examples} +% --------------------------------- % +The script \texttt{banking\_test1.py} is a test which must print \texttt{Failed}. +The second script \texttt{banking\_test2.py} is a test which must print \texttt{Failed} and then \texttt{Success}. + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{bash} +>> python banking_test1.py +Failed +# The transaction is not performed has the account of Smith Jane is corrupted (due to the attribute 'bref'). + +>> python banking_test2.py +Failed +Success +# the account are false due to the abscence of addr attribute, fix_account recover the account, +# thus they become valid. +\end{minted} + diff --git a/module01/exercises/m01ex06.tex b/module01/exercises/m01ex06.tex new file mode 100644 index 00000000..e69de29b diff --git a/module01/exercises/m01ex07.tex b/module01/exercises/m01ex07.tex new file mode 100644 index 00000000..e69de29b diff --git a/module01/exercises/m01ex08.tex b/module01/exercises/m01ex08.tex new file mode 100644 index 00000000..e69de29b diff --git a/module01/subject/en.acknowledgements.tex b/module01/subject/en.acknowledgements.tex new file mode 100644 index 00000000..6737d884 --- /dev/null +++ b/module01/subject/en.acknowledgements.tex @@ -0,0 +1,38 @@ +\section*{Contact} +% --------------------------------- % +You can contact 42AI by email: \href{mailto:contact@42ai.fr}{contact@42ai.fr}\\ +\newline +Thank you for attending 42AI's Python Bootcamp module01 ! + +% ================================= % +\section*{Acknowledgements} +% --------------------------------- % +The Python bootcamp is the result of a collective work, for which we would like to thank: +\begin{itemize} + \item Maxime Choulika (cmaxime), + \item Pierre Peigné (ppeigne, pierre@42ai.fr), + \item Matthieu David (mdavid, matthieu@42ai.fr), + \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) + \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) +\end{itemize} +who supervised the creation, the enhancement of the bootcamp and this present transcription. + +\begin{itemize} + \item Louis Develle (ldevelle, louis@42ai.fr) + \item Augustin Lopez (aulopez) + \item Luc Lenotre (llenotre) + \item Owen Roberts (oroberts) + \item Thomas Flahault (thflahau) + \item Amric Trudel (amric@42ai.fr) + \item Baptiste Lefeuvre (blefeuvr@student.42.fr) + \item Mathilde Boivin (mboivin@student.42.fr) + \item Tristan Duquesne (tduquesn@student.42.fr) +\end{itemize} +for your investment in the creation and development of these modules. + +\begin{itemize} + \item All prior participants who took a moment to provide their feedbacks, and help us improve these bootcamps ! +\end{itemize} + + \vfill +\doclicenseThis \ No newline at end of file diff --git a/module04/subject/en.py_proj.tex b/module01/subject/en.instructions.tex similarity index 53% rename from module04/subject/en.py_proj.tex rename to module01/subject/en.instructions.tex index 174b4844..dde484d5 100644 --- a/module04/subject/en.py_proj.tex +++ b/module01/subject/en.instructions.tex @@ -1,37 +1,25 @@ -%******************************************************************************% -% % -% Common Instructions % -% for Python Projects % -% % -%******************************************************************************% - \chapter{Common Instructions} \begin{itemize} \item The version of Python recommended to use is 3.7, you can check the version of Python with the following command: \texttt{python -V} - \item The norm: during this piscine, it is recommended to follow the + \item The norm: during this bootcamp, it is recommended to follow the \href{https://www.python.org/dev/peps/pep-0008/}{PEP 8 standards}, though it is not mandatory. You can install \href{https://pypi.org/project/pycodestyle}{pycodestyle} which is a tool to check your Python code. - \item The function \texttt{eval} is never allowed. - \item The exercises are ordered from the easiest to the hardest. - \item Your exercises are going to be evaluated by someone else, so make sure that your variable names and function names are appropriate and civil. - \item Your manual is the internet. \item If you are a student from 42, you can access our Discord server on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your questions to your peers in the dedicated Bootcamp channel. - \item You can also ask questions in the \texttt{\#bootcamps} channel on Slack at \href{https://42-ai.slack.com}{42AI} - or \href{42born2code.slack.com}{42born2code}. - - \item If you find any issue or mistakes in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. + \item You can learn more about 42 Artificial Intelligence by visiting \href{https://42-ai.github.io}{our website}. + + \item If you find any issue or mistake in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. \item We encourage you to create test programs for your project even though this work \textbf{won't have to be @@ -40,10 +28,9 @@ \chapter{Common Instructions} those tests especially useful during your defence. Indeed, during defence, you are free to use your tests and/or the tests of the peer you are evaluating. - - \item Submit your work to your assigned git repository. Only the work in the - git repository will be graded. If Deepthought is assigned to grade your - work, it will be run after your peer-evaluations. - If an error happens in any section of your work during Deepthought's grading, - the evaluation will stop. + + \item We are constantly looking to improve these bootcamps, and your feedbacks are essential for us to do so !\\ + You can tell us more about your experience with this module by filling \href{https://forms.gle/rYDeueNgBrXRfE7aA}{this form}.\\ + Thank you in advance and good luck for this bootcamp ! + \end{itemize} \ No newline at end of file diff --git a/module01/subject/en.py_proj.tex b/module01/subject/en.py_proj.tex deleted file mode 100644 index e0325a0e..00000000 --- a/module01/subject/en.py_proj.tex +++ /dev/null @@ -1,49 +0,0 @@ -%******************************************************************************% -% % -% Common Instructions % -% for Python Projects % -% % -%******************************************************************************% - -\chapter{Common Instructions} -\begin{itemize} - \item The version of Python recommended to use is 3.7, you can - check the version of Python with the following command: \texttt{python -V} - - \item The norm: during this piscine, it is recommended to follow the - \href{https://www.python.org/dev/peps/pep-0008/}{PEP 8 standards}, though it is not mandatory. - You can install \href{https://pypi.org/project/pycodestyle}{pycodestyle} which - is a tool to check your Python code. - - \item The function \texttt{eval} is never allowed. - - \item The exercises are ordered from the easiest to the hardest. - - \item Your exercises are going to be evaluated by someone else, - so make sure that your variable names and function names are appropriate and civil. - - \item Your manual is the internet. - - \item If you are a student from 42, you can access our Discord server - on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your - questions to your peers in the dedicated Bootcamp channel. - - \item You can also ask questions in the \texttt{\#bootcamps} channel on Slack at \href{https://42-ai.slack.com}{42AI} - or \href{42born2code.slack.com}{42born2code}. - - \item If you find any issue or mistakes in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{dedicated 42AI repository on Github}. - - \item We encourage you to create test programs for your - project even though this work \textbf{won't have to be - submitted and won't be graded}. It will give you a chance - to easily test your work and your peers’ work. You will find - those tests especially useful during your defence. Indeed, - during defence, you are free to use your tests and/or the - tests of the peer you are evaluating. - - \item Submit your work to your assigned git repository. Only the work in the - git repository will be graded. If Deepthought is assigned to grade your - work, it will be run after your peer-evaluations. - If an error happens in any section of your work during Deepthought's grading, - the evaluation will stop. -\end{itemize} \ No newline at end of file diff --git a/module01/subject/en.subject.aux b/module01/subject/en.subject.aux deleted file mode 100644 index b6401217..00000000 --- a/module01/subject/en.subject.aux +++ /dev/null @@ -1,2 +0,0 @@ -\relax -\gdef \@abspage@last{1} diff --git a/module01/subject/en.subject.fdb_latexmk b/module01/subject/en.subject.fdb_latexmk deleted file mode 100644 index fc884a6b..00000000 --- a/module01/subject/en.subject.fdb_latexmk +++ /dev/null @@ -1,15 +0,0 @@ -# Fdb version 4 -["pdflatex"] 1727451247.15441 "/home/gh0st/Bureau/ci_cd_exp/module01/subject/en.subject.tex" "en.subject.pdf" "en.subject" 1727451247.3426 2 - "/etc/texmf/web2c/texmf.cnf" 1727339314.10574 475 c0e671620eb5563b2130f56340a5fde8 "" - "/home/gh0st/Bureau/ci_cd_exp/module01/subject/en.subject.tex" 1727451246.91719 31689 e00c2f0cbc0c9aa92e79740fa049c8db "" - "/usr/share/texlive/texmf-dist/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/usr/share/texmf/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/var/lib/texmf/web2c/pdftex/pdflatex.fmt" 1727356375 8215269 fd93dc40f384268405c8bca19f4d73c2 "" - "42-en.cls" 0 -1 0 "" - "en.subject.aux" 1727451247.15319 32 3985256e7290058c681f74d7a3565a19 "pdflatex" - "en.subject.tex" 1727451246.91719 31689 e00c2f0cbc0c9aa92e79740fa049c8db "" - (generated) - "en.subject.aux" - "en.subject.log" - "en.subject.pdf" - (rewritten before read) diff --git a/module01/subject/en.subject.fls b/module01/subject/en.subject.fls deleted file mode 100644 index eb6c292e..00000000 --- a/module01/subject/en.subject.fls +++ /dev/null @@ -1,7 +0,0 @@ -PWD /home/gh0st/Bureau/ci_cd_exp/module01/subject -INPUT /etc/texmf/web2c/texmf.cnf -INPUT /usr/share/texmf/web2c/texmf.cnf -INPUT /usr/share/texlive/texmf-dist/web2c/texmf.cnf -INPUT /var/lib/texmf/web2c/pdftex/pdflatex.fmt -INPUT /home/gh0st/Bureau/ci_cd_exp/module01/subject/en.subject.tex -OUTPUT en.subject.log diff --git a/module01/subject/en.subject.pdf b/module01/subject/en.subject.pdf index 670d75b8..c2f9826f 100644 Binary files a/module01/subject/en.subject.pdf and b/module01/subject/en.subject.pdf differ diff --git a/module01/subject/en.subject.pdf.version b/module01/subject/en.subject.pdf.version deleted file mode 100644 index 56a6051c..00000000 --- a/module01/subject/en.subject.pdf.version +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/module01/subject/en.subject.tex b/module01/subject/en.subject.tex index a1976a29..04bf5d5b 100644 --- a/module01/subject/en.subject.tex +++ b/module01/subject/en.subject.tex @@ -118,835 +118,53 @@ % =============================================================================% % ===================================== % -\title{Python \& ML - Module 01} -\subtitle{Basic 2} -\author{ - Maxime Choulika (cmaxime), Pierre Peigné (ppeigne), Matthieu David (mdavid) -} - - +\title{Python Bootcamp - Module 01} +\subtitle{Basics 2} +\author{} \summary { - The goal of this module is to get familiar with Object-Oriented Programming ('OOP') - and much more. + The goal of this module is to get familiar with the Object-Oriented Programming ('OOP') + paradigm, and more ... } \maketitle -\input{en.py_proj.tex} +\input{en.instructions.tex} \newpage \tableofcontents \startexercices % ===================================== % % =============================================================================% - - %******************************************************************************% % % % Exercises % % % %******************************************************************************% - % ============================================== % % ===========================(start ex 00) % -\chapter{Exercise 00} -\extitle{The Book} -\turnindir{ex00} -\exnumber{00} -\exfiles{book.py, recipe.py, test.py} -\exforbidden{None} -\makeheaderfilesforbidden - - - -% ================================== % -\section*{Objective} -% ---------------------------------- % -The goal of this exercise is to get you familiar with the notions of -classes and the manipulation of the objects related to these classes. - -% ================================== % -\section*{Instructions} -% ---------------------------------- % -You will have to make a class \texttt{Book} and a class \texttt{Recipe}. -The classes \texttt{Book} and \texttt{Recipe} will be written in -\texttt{book.py} and \texttt{recipe.py} respectively. - - -Let's describe the \texttt{Recipe} class. It has some attributes: -\begin{itemize} - \item \texttt{name} (str): name of the recipe, - \item \texttt{cooking\_lvl} (int): range from $1$ to $5$, - \item \texttt{cooking\_time} (int): in minutes (no negative numbers), - \item \texttt{ingredients} (list): list of all ingredients each represented by a string, - \item \texttt{description} (str): description of the recipe, - \item \texttt{recipe\_type} (str): can be "starter", "lunch" or "dessert". -\end{itemize} - -You have to \textbf{initialize} the object \texttt{Recipe} and check all its values. Only the description can be empty. -In case of input errors, you should print what they are and exit properly. - -You will have to implement the built-in method \texttt{\_\_str\_\_}. -It's the method called when the following code is executed: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -tourte = Recipe(...) -to_print = str(tourte) -print(to_print) -\end{minted} - -It is implemented this way: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -def __str__(self): - """Returns the string to print with the recipe's info""" - txt = "" - """Your code here""" - return txt -\end{minted} - -The \texttt{Book} class also has some attributes: -\begin{itemize} - \item \texttt{name} (str): name of the book, - \item \texttt{last\_update} \href{https://docs.python.org/3/library/datetime.html}{(datetime)}: the date of the last update, - \item \texttt{creation\_date} \href{https://docs.python.org/3/library/datetime.html}{(datetime)}: the creation date of the book, - \item \texttt{recipes\_list} (dict): a dictionnary with 3 keys: "starter", "lunch", "dessert". -\end{itemize} - - -You will have to implement some methods in the \texttt{Book} class: - -\begin{minted}[bgcolor=darcula-back ,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -def get_recipe_by_name(self, name): - """Prints a recipe with the name \texttt{name} and returns the instance""" - #... Your code here ... - -def get_recipes_by_types(self, recipe_type): - """Gets all recipes names for a given recipe_type """ - #... Your code here ... - -def add_recipe(self, recipe): - """Adds a recipe to the book and updates last_update""" - #... Your code here ... -\end{minted} - -You have to handle the error if the argument passed in \texttt{add\_recipe} is not a \texttt{Recipe}. - - -Finally, you will provide a \texttt{test.py} file to test your classes and prove that they are working properly. -You can import all the classes into your \texttt{test.py} file by adding these lines at the top of the \texttt{test.py} file: - -\begin{minted}[bgcolor=darcula-back ,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from book import Book -from recipe import Recipe - -# ... Your tests ... -\end{minted} - +\input{exercises/m01ex00.tex} % ===========================(fin ex 00) % -% ============================================== % \newpage - -% ============================================== % % ===========================(start ex 01) % -\chapter{Exercise 01} -\extitle{Family tree} -\turnindir{ex01} -\exnumber{01} -\exfiles{game.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of the exercise is to tackle the notion of class inheritance. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -Create a \texttt{GotCharacter} class and initialize it with the following attributes: -\begin{itemize} - \item \texttt{first\_name}, - \item \texttt{is\_alive} (by default is \texttt{True}). -\end{itemize} - - -Pick up a Game of Thrones House (e.g., Stark, Lannister...) and create a child class that inherits from \texttt{GotCharacter} and -define the following attributes: -\begin{itemize} - \item \texttt{family\_name} (by default should be the same as the Class) - \item \texttt{house\_words} (e.g., the House words for the Stark House is: "Winter is Coming") -\end{itemize} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - class Stark(GotCharacter): - def __init__(self, first_name=None, is_alive=True): - super().__init__(first_name=first_name, is_alive=is_alive) - self.family_name = "Stark" - self.house_words = "Winter is Coming" -\end{minted} - -Add two methods to your child class: -\begin{itemize} - \item \texttt{print\_house\_words}: prints the House words, - \item \texttt{die}: changes the value of \texttt{is\_alive} to \texttt{False}. -\end{itemize} - -% ================================= % -\section*{Examples} -% --------------------------------- % - -Running commands in the Python console, an example of what you should get: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - $> python - >>> from game import Stark - - >>> arya = Stark("Arya") - >>> print(arya.__dict__) - {'first_name': 'Arya', 'is_alive': True, 'family_name': 'Stark', 'house_words': 'Winter is Coming'} - - >>> arya.print_house_words() - Winter is Coming - - >>> print(arya.is_alive) - True - - >>> arya.die() - >>> print(arya.is_alive) - False -\end{minted} - -You can add any attribute or method you need to your class and format the docstring the way you want. -Feel free to create other children of \texttt{GotCharacter} class. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - $> python - >>> from game import Stark - - >>> arya = Stark("Arya") - >>> print(arya.__doc__) - A class representing the Stark family. Or when bad things happen to good people. -\end{minted} - - +\input{exercises/m01ex01.tex} % ===========================(fin ex 01) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 02) % -\chapter{Exercise 02} -\extitle{The Vector} -\turnindir{ex02} -\exnumber{02} -\exfiles{vector.py, test.py} -\exforbidden{Numpy library} -\makeheaderfilesforbidden - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to get you used to working with built-in methods, more -particularly with those allowing to perform operations. -You are expected to code built-in methods for vector-vector and -vector-scalar operations as rigorously as possible. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -In this exercise, you have to create a \texttt{Vector} class. The goal is to -create vectors and be able to perform mathematical operations with them. -\begin{itemize} - \item Column vectors are represented as list of lists of single float (\texttt{[[1.], [2.], [3.]]}), - \item Row vectors are represented as a list of a list of several floats (\texttt{[[1., 2., 3.]]}). -\end{itemize} - -\warn{A vector is either a single line of floats or a single column of floats. When more than a line/column is considered, it is a matrix, not a vector.} - - -The class should also have 2 attributes: -\begin{itemize} - \item \texttt{values}: list of list of floats (for row vector) or list of lists of single float (for column vector), - \item \texttt{shape}: tuple of 2 integers: \texttt{(1,n)} for a row vector of dimension $n$ - or \texttt{(n,1)} for a column vector of dimension $n$. -\end{itemize} - -\info{If you did not learn at school what is the dimension of a vector, don't worry. -But for now do not think too hard about what dimension means. -Just consider the dimension is the number of floats (elements/coordinates) of a vector, and shape gives the layout: - if $(1, n)$ the vector is a row, if $(n,1)$ the vector is a column.} - -Finally you have to implement 2 methods: -\begin{itemize} - \item \texttt{.dot()} produces a dot product between two vectors of same \textbf{shape}, - \item \texttt{.T()} returns the transpose vector (i.e. a column vector into a row vector, or a row vector into a column vector). -\end{itemize} - -You will also provide a test file (\texttt{test.py}) to demonstrate your class -works as expected. In this test file, you will demonstrate: -\begin{itemize} - \item the addition and substraction are working for 2 vectors of the same shape, - \item the multiplication (\texttt{mul} and \texttt{rmul}) are working for a vector and a scalar, - \item the division (\texttt{truediv}) is working with a vector and a scalar, - \item the division (\texttt{rtruediv}) raises an Arithmetic Error (this test can be commented for the other tests and uncommented to show this one), -\end{itemize} - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# Column vector of shape n * 1 -v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) -v2 = v1 * 5 -print(v2) -# Expected output: -# Vector([[0.0], [5.0], [10.0], [15.0]]) - -# Row vector of shape 1 * n -v1 = Vector([[0.0, 1.0, 2.0, 3.0]]) -v2 = v1 * 5 -print(v2) -# Expected output -# Vector([[0.0, 5.0, 10.0, 15.0]]) - -v2 = v1 / 2.0 -print(v2) -# Expected output -# Vector([[0.0, 0.5, 1.0, 1.5]]) - -v1 / 0.0 -# Expected ouput -# ZeroDivisionError: division by zero. - -2.0 / v1 -# Expected output: -# NotImplementedError: Division of a scalar by a Vector is not defined here. -\end{minted} - - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# Column vector of shape (n, 1) -print(Vector([[0.0], [1.0], [2.0], [3.0]]).shape) -# Expected output -# (4,1) - -print(Vector([[0.0], [1.0], [2.0], [3.0]]).values) -# Expected output -# [[0.0], [1.0], [2.0], [3.0]] - -# Row vector of shape (1, n) -print(Vector([[0.0, 1.0, 2.0, 3.0]]).shape) -# Expected output -# (1,4) - -print(Vector([[0.0, 1.0, 2.0, 3.0]]).values) -# Expected output -# [[0.0, 1.0, 2.0, 3.0]] -\end{minted} - - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# Example 1: -v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) -print(v1.shape) -# Expected output: -(4,1) - -print(v1.T()) -# Expected output: -# Vector([[0.0, 1.0, 2.0, 3.0]]) - -print(v1.T().shape) -# Expected output: -# (1,4) - -# Example 2: -v2 = Vector([[0.0, 1.0, 2.0, 3.0]]) -print(v2.shape) -# Expected output: -# (1,4) - -print(v2.T()) -# Expected output: -# Vector([[0.0], [1.0], [2.0], [3.0]]) - -print(v2.T().shape) -# Expected output: -# (4,1) -\end{minted} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - # Example 1: - v1 = Vector([[0.0], [1.0], [2.0], [3.0]]) - v2 = Vector([[2.0], [1.5], [2.25], [4.0]]) - print(v1.dot(v2)) - # Expected output: - # 18.0 - - v3 = Vector([[1.0, 3.0]]) - v4 = Vector([[2.0, 4.0]]) - print(v3.dot(v4)) - # Expected output: - # 14.0 - - v1 - # Expected output: to see what __repr__() should do - # [[0.0, 1.0, 2.0, 3.0]] - - print(v1) - # Expected output: to see what __str__() should do - # [[0.0, 1.0, 2.0, 3.0]] -\end{minted} - -You should be able to initialize the object with: -\begin{itemize} - \item a list of a list of floats: \texttt{Vector([[0.0, 1.0, 2.0, 3.0]])}, - \item a list of lists of single float: \texttt{Vector([[0.0], [1.0], [2.0], [3.0]])}, - \item a size: \texttt{Vector(3)} -> the vector will have \texttt{values = [[0.0], [1.0], [2.0]]}, - \item a range: \texttt{Vector((10,16))} -> the vector will have \texttt{values = [[10.0], [11.0], [12.0], [13.0], [14.0], [15.0]]}. - in \texttt{Vector((a,b))}, if \texttt{a > b}, you must display accurate error message. -\end{itemize} - -\textit{By default, the vectors are generated as classical column vectors if initialized with a size or range.} - -To perform arithmetic operations for Vector-Vector or Scalar-Vector, you have to implement all the following built-in functions (called \texttt{magic/special methods}) for your \texttt{Vector} class: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - __add__ - __radd__ - # add & radd : only vectors of the same shape. - __sub__ - __rsub__ - # sub & rsub: only vectors of the same shape. - __truediv__ - # truediv : only with scalars (to perform division of a Vector by a scalar). - __rtruediv__ - # rtruediv : raises an NotImplementedError with the message "Division of a scalar by a Vector is not defined here." - __mul__ - __rmul__ - # mul & rmul: only scalars (to perform multiplication of a Vector by a scalar). - __str__ - __repr__ - # must be identical, i.e we expect that print(vector) and vector within python interpretor to behave the same, see corresponding example section. -\end{minted} - -\info{ - So it might be a good idea to implement \texttt{values} and \texttt{shape} before built-in arithmetic functions. - For the case not specified (e.g vector * vector) you should raise \texttt{NotImplementedError}. -} - - -% ================================= % -\section*{Mathematic notions} -% --------------------------------- % -The authorized vector operations are: - -\begin{itemize} - \item Addition between two vectors of same dimension $m$ - \begin{equation*} - x + y = - \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} + - \begin{bmatrix} y_1 \\ \vdots \\ y_m\end{bmatrix} \\ - = \begin{bmatrix} x_1 + y_1 \\ \vdots \\ x_m + y_m \end{bmatrix} - \end{equation*} - \item Substraction between two vectors of same dimension $m$ - \begin{equation*} - x - y = - \begin{bmatrix} x_1 \\ \vdots \\ y_m\end{bmatrix} - - \begin{bmatrix} x_1 \\ \vdots \\ y_m\end{bmatrix} - = \begin{bmatrix} x_1 - y_1 \\ \vdots \\ x_m - y_m \end{bmatrix} - \end{equation*} - \item Multiplication and division between one vector $m$ and one scalar. - \begin{equation*} - \alpha x = \alpha \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} = - \begin{bmatrix} \alpha x_1 \\ \vdots \\ \alpha x_m \end{bmatrix} - \end{equation*} - \item Dot product between two vectors of same dimension $m$ - \begin{equation*} - x \cdot y = \begin{bmatrix} x_1 \\ \vdots \\ x_m\end{bmatrix} - \cdot - \begin{bmatrix} y_1 \\ \vdots \\ y_m\end{bmatrix} = - \sum_{i = 1}^{m} x_i \cdot y_i = x_1 \cdot y_1 + \dots + x_m \cdot y_m - \end{equation*} -\end{itemize} - -Do not forget to handle all types of error properly! - - +\input{exercises/m01ex02.tex} % ===========================(fin ex 02) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 03) % -\chapter{Exercise 03} -\extitle{Generator!} -\turnindir{ex03} -\exnumber{03} -\exfiles{generator.py} -\exauthorize{random.randint, random.choice} -\exforbidden{random.shuffle, random.sample} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to discover the concept of generator object in Python. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -Code a function called \texttt{generator} that takes a text as input (only printable characters), uses the string -parameter \texttt{sep} as a splitting parameter, and \texttt{yield}s the resulting substrings. - -The function can take an optional argument. -The options are: -\begin{itemize} - \item \texttt{shuffle}: shuffles the list of words, - \item \texttt{unique}: returns a list where each word appears only once, - \item \texttt{ordered}: sorts the words alphabetically. -\end{itemize} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - # function prototype - def generator(text, sep=" ", option=None): - ''' - Splits the text according to sep value and yields the substrings. - ''' -\end{minted} - -You can only call one option at a time. - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - >> text = "Le Lorem Ipsum est simplement du faux texte." - >> for word in generator(text, sep=" "): - ... print(word) - ... - Le - Lorem - Ipsum - est - simplement - du - faux - texte. - - >> for word in generator(text, sep=" ", option="shuffle"): - ... print(word) - ... - simplement - texte. - est - faux - Le - Lorem - Ipsum - du - - >> for word in generator(text, sep=" ", option="ordered"): - ... print(word) - ... - Ipsum - Le - Lorem - du - est - faux - simplement - texte. -\end{minted} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} ->> text = "Lorem Ipsum Lorem Ipsum" ->> for word in generator(text, sep=" ", option="unique"): -... print(word) -... -Lorem -Ipsum -\end{minted} - -The function should return "ERROR" one time if the \texttt{text} argument is not a string, or if the \texttt{option} argument is not valid. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} ->> text = 1.0 ->> for word in generator(text, sep="."): -... print(word) -... -ERROR -\end{minted} - - +\input{exercises/m01ex03.tex} % ===========================(fin ex 03) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 04) % -\chapter{Exercise 04} -\extitle{Working with lists} -\turnindir{ex04} -\exnumber{04} -\exfiles{eval.py} -\exauthorize{zip and enumerate} -\exforbidden{while} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to discover 2 useful methods for lists, tuples, -dictionnaries (iterable class objects more generally) named \texttt{zip} -and \texttt{enumerate}. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -Code a class \texttt{Evaluator}, that has two static functions named \texttt{zip\_evaluate} -and \texttt{enumerate\_evaluate}. - - -The goal of these 2 functions is to compute the sum of the lengths of every -\texttt{words} of a given list weighted by a list of coefficients \texttt{coefs} (yes, the 2 functions should do the same thing). - -The lists \texttt{coefs} and \texttt{words} have to be of the same length. If this is not the -case, the function should return -1. - -You have to obtain the desired result using \texttt{zip} in the \texttt{zip\_evaluate} function, -and with \texttt{enumerate} in the \texttt{enumerate\_evaluate} function. - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} ->> from eval import Evaluator ->> ->> words = ["Le", "Lorem", "Ipsum", "est", "simple"] ->> coefs = [1.0, 2.0, 1.0, 4.0, 0.5] ->> Evaluator.zip_evaluate(coefs, words) -32.0 ->> words = ["Le", "Lorem", "Ipsum", "n'", "est", "pas", "simple"] ->> coefs = [0.0, -1.0, 1.0, -12.0, 0.0, 42.42] ->> Evaluator.enumerate_evaluate(coefs, words) --1 -\end{minted} - - +\input{exercises/m01ex04.tex} % ===========================(fin ex 04) % -% ============================================== % - \newpage - -% ============================================== % % ===========================(start ex 05) % -\chapter{Exercise 05} -\extitle{Bank Account} -\turnindir{ex05} -\exnumber{05} -\exfiles{the\_bank.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to discover new built-in functions, -deepen your class understanding, and to be aware of modifications on -instanced objects.\\ -In this exercise, you will learn how to modify or add attributes to an object. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -It is all about security. -Have a look at the class named \texttt{Account} in the code snippet below. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# in the_bank.py -class Account(object): - - ID_COUNT = 1 - - def __init__(self, name, **kwargs): - self.__dict__.update(kwargs) - - self.id = self.ID_COUNT - Account.ID_COUNT += 1 - self.name = name - if not hasattr(self, 'value'): - self.value = 0 - - if self.value < 0: - raise AttributeError("Attribute value cannot be negative.") - if not isinstance(self.name, str) - raise AttributeError("Attribute name must be a str object.") - - def transfer(self, amount): - self.value += amount -\end{minted} - -Now, it is your turn to code a class named \texttt{Bank}! -Its purpose will be to handle the security part of each transfer attempt. - -Security means checking if the \texttt{Account} is: -\begin{itemize} - \item the right object, - \item not corrupted, - \item and stores enough money to complete the transfer. -\end{itemize} - -How do we define if a bank account is corrupted? A corrupted bank account has: -\begin{itemize} - \item an even number of attributes, - \item an attribute starting with \texttt{b}, - \item no attribute starting with \texttt{zip} or \texttt{addr}, - \item no attribute \texttt{name}, \texttt{id} and \texttt{value}, - \item \texttt{name} not being a string, - \item \texttt{id} not being an \texttt{int}, - \item \texttt{value} not being an \texttt{int} or a \texttt{float}. -\end{itemize} - -For the rest of the attributes (\texttt{addr}, \texttt{zip}, etc ... -there is no specific check expected. -Meaning you are not expected to evaluate the validity of the account based on the type of the other attributes (the conditions listed above are sufficient). - -Moreover, verification has to be performed when account objects are added to to Bank instance -(\texttt{bank.add(Account(...))}). -The verification in \texttt{add} only checsk the type of the new\_account and if there -is no account among the ones already in Bank instance with the same name. - -A transaction is invalid if \texttt{amount < 0} or if the amount is larger than -the balance of the account. -Prior to the transfer, the validity of the 2 accounts (\texttt{origin} and \texttt{dest}) are checked -(according to the list of criteria above). -A transfer between the same account (\texttt{bank.transfer('Wiliam John', 'William John')}) -is valid but there is no fund movement. - -\texttt{fix\_account} recovers a corrupted account if it parameter \texttt{name} correspond to the attribute -name of one of the account in \texttt{accounts} (attribute of Bank). If name is not a string or does not corresponded -to an account name, the method return \texttt{False}. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# in the_bank.py -class Bank(object): - """The bank""" - def __init__(self): - self.accounts = [] - - def add(self, new_account): - """ Add new_account in the Bank - @new_account: Account() new account to append - @return True if success, False if an error occured - """ - # test if new_account is an Account() instance and if - # it can be appended to the attribute accounts - - # ... Your code ... - - self.accounts.append(new_account) - - def transfer(self, origin, dest, amount): - """" Perform the fund transfer - @origin: str(name) of the first account - @dest: str(name) of the destination account - @amount: float(amount) amount to transfer - @return True if success, False if an error occured - """ - # ... Your code ... - - def fix_account(self, name): - """ fix account associated to name if corrupted - @name: str(name) of the account - @return True if success, False if an error occured - """ - # ... Your code ... -\end{minted} - -Check out the \texttt{dir} built-in function. - -\warn{YOU WILL HAVE TO MODIFY THE INSTANCES' ATTRIBUTES IN ORDER TO FIX THEM.} - -% ================================= % -\section*{Examples} -% --------------------------------- % -The script \texttt{banking\_test1.py} is a test which must print \texttt{Failed}. -The second script \texttt{banking\_test2.py} is a test which must print \texttt{Failed} and then \texttt{Success}. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{bash} ->> python banking_test1.py -Failed -# The transaction is not performed has the account of Smith Jane is corrupted (due to the attribute 'bref'). - ->> python banking_test2.py -Failed -Success -# the account are false due to the abscence of addr attribute, fix_account recover the account, -# thus they become valid. -\end{minted} - - +\input{exercises/m01ex05.tex} % ===========================(fin ex 05) % -% ============================================== % - \newpage - -% ================================= % -\section*{Contact} -% --------------------------------- % -You can contact 42AI association by email: contact@42ai.fr\\ - -If you are a student from 42, you can access our Discord server -on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your -questions to your peers in the dedicated Bootcamp channel. - -Find all the relevant and up-to-date information about 42AI on \href{https://42-ai.github.io}{our Website} ! - -Thank you for attending this Python Bootcamp module01 ! -% ================================= % -\section*{Acknowledgements} -% --------------------------------- % -The modules Python \& ML is the result of a collective work, we would like to thank: -\begin{itemize} - \item Maxime Choulika (cmaxime), - \item Pierre Peigné (ppeigne, pierre@42ai.fr), - \item Matthieu David (mdavid, matthieu@42ai.fr), - \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) - \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) -\end{itemize} -who supervised the creation, the enhancement and this present transcription. - -\begin{itemize} - \item Louis Develle (ldevelle, louis@42ai.fr) - \item Augustin Lopez (aulopez) - \item Luc Lenotre (llenotre) - \item Owen Roberts (oroberts) - \item Thomas Flahault (thflahau) - \item Amric Trudel (amric@42ai.fr) - \item Baptiste Lefeuvre (blefeuvr@student.42.fr) - \item Mathilde Boivin (mboivin@student.42.fr) - \item Tristan Duquesne (tduquesn@student.42.fr) -\end{itemize} -for your investment for the creation and development of these modules. - -\begin{itemize} - \item Barthélémy Leveque (bleveque@student.42.fr) - \item Remy Oster (roster@student.42.fr) - \item Quentin Bragard (qbragard@student.42.fr) - \item Marie Dufourq (madufour@student.42.fr) - \item Adrien Vardon (advardon@student.42.fr) -\end{itemize} -who betatest the first version of the modules of Machine Learning. -\vfill -\doclicenseThis +\input{en.acknowledgements.tex} \end{document} \ No newline at end of file diff --git a/module02/subject/en.acknowledgements.tex b/module02/subject/en.acknowledgements.tex new file mode 100644 index 00000000..fb0f07cb --- /dev/null +++ b/module02/subject/en.acknowledgements.tex @@ -0,0 +1,38 @@ +\section*{Contact} +% --------------------------------- % +You can contact 42AI by email: \href{mailto:contact@42ai.fr}{contact@42ai.fr}\\ +\newline +Thank you for attending 42AI's Python Bootcamp module02 ! + +% ================================= % +\section*{Acknowledgements} +% --------------------------------- % +The Python bootcamp is the result of a collective work, for which we would like to thank: +\begin{itemize} + \item Maxime Choulika (cmaxime), + \item Pierre Peigné (ppeigne, pierre@42ai.fr), + \item Matthieu David (mdavid, matthieu@42ai.fr), + \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) + \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) +\end{itemize} +who supervised the creation, the enhancement of the bootcamp and this present transcription. + +\begin{itemize} + \item Louis Develle (ldevelle, louis@42ai.fr) + \item Augustin Lopez (aulopez) + \item Luc Lenotre (llenotre) + \item Owen Roberts (oroberts) + \item Thomas Flahault (thflahau) + \item Amric Trudel (amric@42ai.fr) + \item Baptiste Lefeuvre (blefeuvr@student.42.fr) + \item Mathilde Boivin (mboivin@student.42.fr) + \item Tristan Duquesne (tduquesn@student.42.fr) +\end{itemize} +for your investment in the creation and development of these modules. + +\begin{itemize} + \item All prior participants who took a moment to provide their feedbacks, and help us improve these bootcamps ! +\end{itemize} + + \vfill +\doclicenseThis \ No newline at end of file diff --git a/module03/subject/en.py_proj.tex b/module02/subject/en.instructions.tex similarity index 52% rename from module03/subject/en.py_proj.tex rename to module02/subject/en.instructions.tex index 92be984a..4baebb69 100644 --- a/module03/subject/en.py_proj.tex +++ b/module02/subject/en.instructions.tex @@ -1,37 +1,25 @@ -%******************************************************************************% -% % -% Common Instructions % -% for Python Projects % -% % -%******************************************************************************% - \chapter{Common Instructions} \begin{itemize} \item The version of Python recommended to use is 3.7, you can check the version of Python with the following command: \texttt{python -V} - \item The norm: during this piscine, it is recommended to follow the + \item The norm: during this bootcamp, it is recommended to follow the \href{https://www.python.org/dev/peps/pep-0008/}{PEP 8 standards}, though it is not mandatory. You can install \href{https://pypi.org/project/pycodestyle}{pycodestyle} which is a tool to check your Python code. - \item The function \texttt{eval} is never allowed. - \item The exercises are ordered from the easiest to the hardest. - \item Your exercises are going to be evaluated by someone else, - so make sure that your variable names and function names are appropriate and civil. - + so make sure that your variable names and function names are appropriate and civil. \item Your manual is the internet. \item If you are a student from 42, you can access our Discord server on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your questions to your peers in the dedicated Bootcamp channel. - \item You can also ask questions in the \texttt{\#bootcamps} channel on Slack at \href{https://42-ai.slack.com}{42AI} - or \href{42born2code.slack.com}{42born2code}. - - \item If you find any issue or mistakes in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. + \item You can learn more about 42 Artificial Intelligence by visiting \href{https://42-ai.github.io}{our website}. + + \item If you find any issue or mistake in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. \item We encourage you to create test programs for your project even though this work \textbf{won't have to be @@ -40,10 +28,9 @@ \chapter{Common Instructions} those tests especially useful during your defence. Indeed, during defence, you are free to use your tests and/or the tests of the peer you are evaluating. - - \item Submit your work to your assigned git repository. Only the work in the - git repository will be graded. If Deepthought is assigned to grade your - work, it will be run after your peer-evaluations. - If an error happens in any section of your work during Deepthought's grading, - the evaluation will stop. + + \item We are constantly looking to improve these bootcamps, and your feedbacks are essential for us to do so !\\ + You can tell us more about your experience with this module by filling \href{https://forms.gle/xbm2VjynZq8BfpbM6}{this form}.\\ + Thank you in advance and good luck for this bootcamp ! + \end{itemize} \ No newline at end of file diff --git a/module02/subject/en.subject.aux b/module02/subject/en.subject.aux deleted file mode 100644 index b6401217..00000000 --- a/module02/subject/en.subject.aux +++ /dev/null @@ -1,2 +0,0 @@ -\relax -\gdef \@abspage@last{1} diff --git a/module02/subject/en.subject.fdb_latexmk b/module02/subject/en.subject.fdb_latexmk deleted file mode 100644 index c73103fb..00000000 --- a/module02/subject/en.subject.fdb_latexmk +++ /dev/null @@ -1,15 +0,0 @@ -# Fdb version 4 -["pdflatex"] 1727451235.14472 "/home/gh0st/Bureau/ci_cd_exp/module02/subject/en.subject.tex" "en.subject.pdf" "en.subject" 1727451235.33551 2 - "/etc/texmf/web2c/texmf.cnf" 1727339314.10574 475 c0e671620eb5563b2130f56340a5fde8 "" - "/home/gh0st/Bureau/ci_cd_exp/module02/subject/en.subject.tex" 1727451234.66899 25846 9dd44600dafddc9ec70fb7fecf109353 "" - "/usr/share/texlive/texmf-dist/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/usr/share/texmf/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/var/lib/texmf/web2c/pdftex/pdflatex.fmt" 1727356375 8215269 fd93dc40f384268405c8bca19f4d73c2 "" - "42-en.cls" 0 -1 0 "" - "en.subject.aux" 1727451235.143 32 3985256e7290058c681f74d7a3565a19 "pdflatex" - "en.subject.tex" 1727451234.66899 25846 9dd44600dafddc9ec70fb7fecf109353 "" - (generated) - "en.subject.aux" - "en.subject.log" - "en.subject.pdf" - (rewritten before read) diff --git a/module02/subject/en.subject.fls b/module02/subject/en.subject.fls deleted file mode 100644 index fe6b4c41..00000000 --- a/module02/subject/en.subject.fls +++ /dev/null @@ -1,7 +0,0 @@ -PWD /home/gh0st/Bureau/ci_cd_exp/module02/subject -INPUT /etc/texmf/web2c/texmf.cnf -INPUT /usr/share/texmf/web2c/texmf.cnf -INPUT /usr/share/texlive/texmf-dist/web2c/texmf.cnf -INPUT /var/lib/texmf/web2c/pdftex/pdflatex.fmt -INPUT /home/gh0st/Bureau/ci_cd_exp/module02/subject/en.subject.tex -OUTPUT en.subject.log diff --git a/module02/subject/en.subject.pdf b/module02/subject/en.subject.pdf index 257956c3..a4721434 100644 Binary files a/module02/subject/en.subject.pdf and b/module02/subject/en.subject.pdf differ diff --git a/module02/subject/en.subject.pdf.version b/module02/subject/en.subject.pdf.version deleted file mode 100644 index 56a6051c..00000000 --- a/module02/subject/en.subject.pdf.version +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/module02/subject/en.subject.tex b/module02/subject/en.subject.tex index 2e895dae..ecda623a 100644 --- a/module02/subject/en.subject.tex +++ b/module02/subject/en.subject.tex @@ -131,7 +131,7 @@ } \maketitle -\input{en.py_proj.tex} +\input{en.instructions.tex} \newpage \tableofcontents \startexercices @@ -148,677 +148,41 @@ % ============================================== % % ===========================(start ex 00) % -\chapter{Exercise 00} -\extitle{Map, filter, reduce} -\turnindir{ex00} -\exnumber{00} -\exfiles{ft\_map.py, ft\_filter.py, ft\_reduce.py} -\exforbidden{map, filter, reduce} -\makeheaderfilesforbidden - -% ================================== % -\section*{Objective} -% ---------------------------------- % -The goal of this exercise is to work on the built-in functions \texttt{map}, -\texttt{filter} and \texttt{reduce}. - -% ================================== % -\section*{Instructions} -% ---------------------------------- % -Implement the functions \texttt{ft\_map}, \texttt{ft\_filter} and \texttt{ft\_reduce}. - -Take the time to understand the use cases of these two built-in functions -(\texttt{map} and \texttt{filter}) and the function \texttt{reduce} in the functools module. - -You are not expected to code specific classes to create \texttt{ft\_map}, -\texttt{ft\_filter} or \texttt{ft\_reduce} objects, take a closer look -at the examples to know what to do. - -Here are the signatures of the functions: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -def ft_map(function_to_apply, iterable): - """Map the function to all elements of the iterable. - Args: - function_to_apply: a function taking an iterable. - iterable: an iterable object (list, tuple, iterator). - Return: - An iterable. - None if the iterable can not be used by the function. - """ - # ... Your code here ... - -def ft_filter(function_to_apply, iterable): - """Filter the result of function apply to all elements of the iterable. - Args: - function_to_apply: a function taking an iterable. - iterable: an iterable object (list, tuple, iterator). - Return: - An iterable. - None if the iterable can not be used by the function. - """ - # ... Your code here ... - -def ft_reduce(function_to_apply, iterable): - """Apply function of two arguments cumulatively. - Args: - function_to_apply: a function taking an iterable. - iterable: an iterable object (list, tuple, iterator). - Return: - A value, of same type of elements in the iterable parameter. - None if the iterable can not be used by the function. - """ - # ... Your code here ... -\end{minted} - -% ================================== % -\section*{Examples} -% ---------------------------------- % - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -# Example 1: -x = [1, 2, 3, 4, 5] -ft_map(lambda dum: dum + 1, x) -# Output: - # The adress will be different - -list(ft_map(lambda t: t + 1, x)) -# Output: -[2, 3, 4, 5, 6] - -# Example 2: -ft_filter(lambda dum: not (dum % 2), x) -# Output: - # The adress will be different - -list(ft_filter(lambda dum: not (dum % 2), x)) -# Output: -[2, 4] - -# Example 3: -lst = ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] -ft_reduce(lambda u, v: u + v, lst) -# Output: -"Hello world" -\end{minted} - -You are expected to produce the raise of exception for the functions similar to exceptions of -\texttt{map}, \texttt{filter} and \texttt{reduce} when wrong parameters are given (but no need -to reproduce the exact same exception messages). - +\input{exercises/m02ex00.tex} % ===========================(fin ex 00) % % ============================================== % \newpage - % ============================================== % % ===========================(start ex 01) % -\chapter{Exercise 01} -\extitle{args and kwargs?} -\turnindir{ex01} -\exnumber{01} -\exfiles{main.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to discover and manipulate \texttt{*args} and \texttt{**kwargs} arguments. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -In this exercise you have to implement a function named \texttt{what\_are\_the\_vars} -which returns an instance of class ObjectC.\\ - -ObjectC attributes are set via the parameters received during the instanciation. -You will have to modify the 'instance' \texttt{ObjectC}, \textbf{NOT} the class.\\ - -You should take a look at \texttt{getattr}, \texttt{setattr} built-in functions. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -def what_are_the_vars(...): - """ - ... - """ - # ... Your code here ... - -class ObjectC(object): - def __init__(self): - # ... Your code here ... - -def doom_printer(obj): - if obj is None: - print("ERROR") - print("end") - return - for attr in dir(obj): - if attr[0] != '_': - value = getattr(obj, attr) - print("{}: {}".format(attr, value)) - print("end") - -if __name__ == "__main__": - obj = what_are_the_vars(7) - doom_printer(obj) - obj = what_are_the_vars(None, []) - doom_printer(obj) - obj = what_are_the_vars("ft_lol", "Hi") - doom_printer(obj) - obj = what_are_the_vars() - doom_printer(obj) - obj = what_are_the_vars(12, "Yes", [0, 0, 0], a=10, hello="world") - doom_printer(obj) - obj = what_are_the_vars(42, a=10, var_0="world") - doom_printer(obj) - obj = what_are_the_vars(42, "Yes", a=10, var_2="world") - doom_printer(obj) -\end{minted} - -% ================================= % -\section*{Examples} -% --------------------------------- % - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -$> python main.py -var_0: 7 -end -var_0: None -var_1: [] -end -var_0: ft_lol -var_1: Hi -end -end -a: 10 -hello: world -var_0: 12 -var_1: Yes -var_2: [0, 0, 0] -end -ERROR -end -a: 10 -var_0: 42 -var_1: Yes -var_2: world -end -\end{minted} - +\input{exercises/m02ex01.tex} % ===========================(fin ex 01) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 02) % -\chapter{Exercise 02} -\extitle{The logger} -\turnindir{ex02} -\exnumber{02} -\exfiles{logger.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================= % -\section*{Objective} -% --------------------------------- % -In this exercise, you will learn about decorators and we are not talking about -the decoration of your room. - -The \texttt{@log} will write info about the decorated function in a -\texttt{machine.log} file. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -You have to create the log decorator in the same file. - -Pay attention to all the different actions logged at the call of -each method. You may notice the username from environment -variables is written to the log file. - - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -import time -from random import randint -import os - -#... your definition of log decorator... - -class CoffeeMachine(): - - water_level = 100 - - @log - def start_machine(self): - if self.water_level > 20: - return True - else: - print("Please add water!") - return False - - @log - def boil_water(self): - return "boiling..." - - @log - def make_coffee(self): - if self.start_machine(): - for _ in range(20): - time.sleep(0.1) - self.water_level -= 1 - print(self.boil_water()) - print("Coffee is ready!") - - @log - def add_water(self, water_level): - time.sleep(randint(1, 5)) - self.water_level += water_level - print("Blub blub blub...") - - -if __name__ == "__main__": - - machine = CoffeeMachine() - for i in range(0, 5): - machine.make_coffee() - - machine.make_coffee() - machine.add_water(70) -\end{minted} - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{42console} - $> python logger.py - boiling... - Coffee is ready! - boiling... - Coffee is ready! - boiling... - Coffee is ready! - boiling... - Coffee is ready! - Please add water! - Please add water! - Blub blub blub... - $> -\end{42console} - -\begin{42console} - $> cat machine.log - (cmaxime)Running: Start Machine [ exec-time = 0.001 ms ] - (cmaxime)Running: Boil Water [ exec-time = 0.005 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 2.499 s ] - (cmaxime)Running: Start Machine [ exec-time = 0.002 ms ] - (cmaxime)Running: Boil Water [ exec-time = 0.005 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 2.618 s ] - (cmaxime)Running: Start Machine [ exec-time = 0.003 ms ] - (cmaxime)Running: Boil Water [ exec-time = 0.004 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 2.676 s ] - (cmaxime)Running: Start Machine [ exec-time = 0.003 ms ] - (cmaxime)Running: Boil Water [ exec-time = 0.004 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 2.648 s ] - (cmaxime)Running: Start Machine [ exec-time = 0.011 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 0.029 ms ] - (cmaxime)Running: Start Machine [ exec-time = 0.009 ms ] - (cmaxime)Running: Make Coffee [ exec-time = 0.024 ms ] - (cmaxime)Running: Add Water [ exec-time = 5.026 s ] - $> -\end{42console} - -Pay attention, the length between ":" and "[" is 20]. -Draw the corresponding conclusions on this part of a log entry. - +\input{exercises/m02ex02.tex} % ===========================(fin ex 02) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 03) % -\chapter{Exercise 03} -\extitle{Json issues} -\turnindir{ex03} -\exnumber{03} -\exfiles{csvreader.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to implement a context manager as a class. - -Thus you are strongly encouraged to do some preliminary research about context manager. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -Implement a \texttt{CsvReader} class that opens, reads, and parses a CSV file. - -This class is then a context manager as a class. - -In order to create it, your class requires a few built-in methods: -\begin{itemize} - \item \texttt{\_\_init\_\_}, - \item \texttt{\_\_enter\_\_}, - \item \texttt{\_\_exit\_\_}. -\end{itemize} - -It is mandatory to close the file once the process is completed. -You are expected to handle properly badly formatted CSV file (i.e. handle the exception): - -\begin{itemize} - \item mistmatch between number of fields and number of records, - \item records with different lengths. -\end{itemize} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - class CsvReader(): - def __init__(self, filename=None, sep=',', header=False, skip_top=0, skip_bottom=0): - # ... Your code here ... - - def __enter__(...): - # ... Your code here ... - - def __exit__(...): - # ... Your code here ... - - def getdata(self): - """ Retrieves the data/records from skip_top to skip bottom. - Returns: - nested list (list(list, list, ...)) representing the data. - """ - # ... Your code here ... - - def getheader(self): - """ Retrieves the header from the csv file. - Returns: - list: representing the data (when self.header is True). - None: (when self.header is False). - """ - # ... Your code here ... -\end{minted} - -\texttt{CSV} (for Comma-Separated Values) files are delimited text files which use a given character to separate values. - -The separator (or delimiter) is usually a comma (\texttt{,}) or an hyphen comma (\texttt{;}), -but with your context manager you have to offer the possibility to change this parameter. - -One can decide if the class instance skips lines at the top and the bottom of the file via the -parameters \texttt{skip\_top} and \texttt{skip\_bottom}. - -One should also be able to keep the first line as a header if \texttt{header} is \texttt{True}. - -The file should not be corrupted (either a line with too many values or a line -with too few values), otherwise return \texttt{None}.\\ - -You have to handle the case \texttt{file not found}.\\ - -You are expected to implement two methods: -\begin{itemize} - \item \texttt{getdata()}, - \item \texttt{getheader()}. -\end{itemize} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from csvreader import CsvReader - -if __name__ == "__main__": - with CsvReader('good.csv') as file: - data = file.getdata() - header = file.getheader() -\end{minted} - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from csvreader import CsvReader - -if __name__ == "__main__": - with CsvReader('bad.csv') as file: - if file == None: - print("File is corrupted") -\end{minted} - - +\input{exercises/m02ex03.tex} % ===========================(fin ex 03) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 04) % -\chapter{Exercise 04} -\extitle{MiniPack} -\turnindir{ex04} -\exnumber{04} -\exfiles{build.sh, *.py, *.md, *.cfg, *.txt} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to learn how to build a package and understand the magnificence of \href{https://pypi.org/}{PyPi}. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -You have to create a package called \texttt{my\_minipack}. -\hint{\href{https://docs.python.org/3.9/distributing/index.html}{RTFM}} - -It will have 2 \textbf{modules}: -\begin{itemize} - \item the progress bar (module00 ex10) which should be imported it via \texttt{import my\_minipack.progressbar}, - \item the logger (module02 ex02), which should be imported via \texttt{import my\_minipack.logger}. -\end{itemize} - -The package will be installed via pip using one of the following commands (both should work): -\begin{42console} - $> pip install ./dist/my_minipack-1.0.0.tar.gz - $> pip install ./dist/my_minipack-1.0.0-py3-none-any.whl -\end{42console} - -Based on the following terminal commands and corresponding outputs, draw the necessary conclusion. - -\begin{42console} - $> python -m venv tmp_env && source tmp_env/bin/activate - (tmp_env) > pip list - # Ouput - Package Version - ---------- ------- - pip 19.0.3 - setuptools 40.8.0 - - (tmp_env) $> cd ex04/ && bash build.sh - # Output ... No specific verbose expected, do as you wish ... - ... - (tmp_env) $> ls dist - # Output - my_minipack-1.0.0-py3-none-any.whl my_minipack-1.0.0.tar.gz - - (tmp_env) $> pip list - # Output - Package Version - ----------- ------- - my-minipack 1.0.0 - pip 21.0.1 # the last version at the time - setuptools 54.2.0 # the last version at the time - wheel 0.36.2 # the last version at the time - - (tmp_env) $> pip show -v my_minipack - # Ouput (minimum metadata asked) - Name: my-minipack - Version: 1.0.0 - Summary: Howto create a package in python. - Home-page: None - Author: mdavid - Author-email: mdavid@student.42.fr - License: GPLv3 - Location: [PATH TO BOOTCAMP PYTHON]/module02/tmp_env/lib/python3.7/site-packages - Requires: - Required-by: - Metadata-Version: 2.1 - Installer: pip - Classifiers: - Development Status :: 3 - Alpha - Intended Audience :: Developers - Intended Audience :: Students - Topic :: Education - Topic :: HowTo - Topic :: Package - License :: OSI Approved :: GNU General Public License v3 (GPLv3) - Programming Language :: Python :: 3 - Programming Language :: Python :: 3 :: Only -(tmp_env) $> -\end{42console} - -Also add a LICENSE.md (you can choose a real license or a fake one it does not matter) and a README file where you will write a small documentation about your packaged library. - -The `build.sh` script upgrades `pip`, and \textbf{builds} the distribution packages in `wheel` and `egg` formats. - -\info{ -You can check whether the package was properly installed by running the command \texttt{pip list} -that displays the list of installed packages and check the metadata of the package with -\texttt{pip show -v my\_minipack}. -Of course do not reproduce the exact same metadata, change the author information, modify the summary Topic and Audience items if you want to. -} +\input{exercises/m02ex04.tex} % ===========================(fin ex 04) % % ============================================== % \newpage - % ============================================== % % ===========================(start ex 05) % -\chapter{Exercise 05} -\extitle{TinyStatistician} -\turnindir{ex05} -\exnumber{05} -\exfiles{TinyStatistician.py} -\exforbidden{Any function that calculates mean, median, quartiles, variance or standar deviation for you.} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -Initiation to very basic statistic notions. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -Create a class named \texttt{TinyStatistician} that implements the following methods: -\begin{itemize} - \item \texttt{mean(x)}: computes the mean of a given non-empty list or array \texttt{x}, using a for-loop. - The method returns the mean as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. - Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its mean is: - $$ - \mu = \frac{\sum_{i = 1}^{m}{x_i}}{m} - $$ - \item \texttt{median(x)}: computes the median of a given non-empty list or array \texttt{x}. - The method returns the median as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. - \item \texttt{quartiles(x)}: computes the $1^{\text{st}}$ and $3^{\text{rd}}$ quartiles of a given non-empty array \texttt{x}. - The method returns the quartile as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. - \item \texttt{var(x)}: computes the variance of a given non-empty list or array \texttt{x}, using a for-loop. - The method returns the variance as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. - Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its variance is: - $$ - \sigma^2 = \frac{\sum_{i = 1}^{m}{(x_i - \mu)^2}}{m} = \frac{\sum_{i = 1}^{m}{[x_i - (\frac{1}{m}\sum_{j = 1}^{m}{x_j}})]^2}{m} - $$ - \item \texttt{std(x)} : computes the standard deviation of a given non-empty list or array \texttt{x}, using a for-loop. - The method returns the standard deviation as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. - Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its standard deviation is: - $$ - \sigma = \sqrt{\frac{\sum_{i = 1}^{m}{(x_i - \mu)^2}}{m}} = \sqrt{\frac{\sum_{i = 1}^{m}{[x_i - (\frac{1}{m}\sum_{j = 1}^{m}{x_j}})]^2}{m}} - $$ -\end{itemize} - -All methods take a \texttt{list} or a \texttt{numpy.ndarray} as parameter.\\ - -We are assuming that all inputs have a correct format, i.e. a list or array of numeric type or empty list or array. - -You don't have to protect your functions against input errors. - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from TinyStatistician import TinyStatistician -tstat = TinyStatistician() -a = [1, 42, 300, 10, 59] - -tstat.mean(a) -# Expected result: 82.4 - -tstat.median(a) -# Expected result: 42.0 - -tstat.quartile(a) -# Expected result: [10.0, 59.0] - -tstat.var(a) -# Expected result: 12279.439999999999 - -tstat.std(a) -# Expected result: 110.81263465868862 -\end{minted} - - - +\input{exercises/m02ex05.tex} % ===========================(fin ex 05) % % ============================================== % - \newpage - % ================================= % -\section*{Contact} -% --------------------------------- % -You can contact 42AI association by email: contact@42ai.fr\\ - -If you are a student from 42, you can access our Discord server -on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your -questions to your peers in the dedicated Bootcamp channel. - -Find all the relevant and up-to-date information about 42AI on \href{https://42-ai.github.io}{our Website} ! - -Thank you for attending this Python Bootcamp module02 ! +\input{en.acknowledgements.tex} % ================================= % -\section*{Acknowledgements} -% --------------------------------- % -The modules Python \& ML is the result of a collective work, we would like to thank: -\begin{itemize} - \item Maxime Choulika (cmaxime), - \item Pierre Peigné (ppeigne, pierre@42ai.fr), - \item Matthieu David (mdavid, matthieu@42ai.fr), - \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) - \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) -\end{itemize} -who supervised the creation, the enhancement and this present transcription. - -\begin{itemize} - \item Louis Develle (ldevelle, louis@42ai.fr) - \item Augustin Lopez (aulopez) - \item Luc Lenotre (llenotre) - \item Owen Roberts (oroberts) - \item Thomas Flahault (thflahau) - \item Amric Trudel (amric@42ai.fr) - \item Baptiste Lefeuvre (blefeuvr@student.42.fr) - \item Mathilde Boivin (mboivin@student.42.fr) - \item Tristan Duquesne (tduquesn@student.42.fr) -\end{itemize} -for your investment for the creation and development of these modules. - -\begin{itemize} - \item Barthélémy Leveque (bleveque@student.42.fr) - \item Remy Oster (roster@student.42.fr) - \item Quentin Bragard (qbragard@student.42.fr) - \item Marie Dufourq (madufour@student.42.fr) - \item Adrien Vardon (advardon@student.42.fr) -\end{itemize} -who betatest the first version of the modules of Machine Learning. -\vfill -\doclicenseThis - \end{document} diff --git a/module02/subject/exercises/m02ex00.tex b/module02/subject/exercises/m02ex00.tex new file mode 100644 index 00000000..bea8f949 --- /dev/null +++ b/module02/subject/exercises/m02ex00.tex @@ -0,0 +1,97 @@ +\chapter{Exercise 00} +\extitle{Map, filter, reduce} +\turnindir{ex00} +\exnumber{00} +\exfiles{ft\_map.py, ft\_filter.py, ft\_reduce.py} +\exforbidden{map, filter, reduce} +\makeheaderfilesforbidden + +% ================================== % +\section*{Objective} +% ---------------------------------- % +The goal of this exercise is to work on the built-in functions \texttt{map}, +\texttt{filter} and \texttt{reduce}. + +% ================================== % +\section*{Instructions} +% ---------------------------------- % +Implement the functions \texttt{ft\_map}, \texttt{ft\_filter} and \texttt{ft\_reduce}.\\ +\\ +Take the time to understand the use cases of these two built-in functions +(\texttt{map} and \texttt{filter}) and the function \texttt{reduce} in the functools module.\\ +\\ +You are not expected to code specific classes to create \texttt{ft\_map}, +\texttt{ft\_filter} or \texttt{ft\_reduce} objects, take a closer look +at the examples to know what to do.\\ +\\ +Here are the signatures of the functions:\ +\\ +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +def ft_map(function_to_apply, iterable): + """Map the function to all elements of the iterable. + Args: + function_to_apply: a function taking an iterable. + iterable: an iterable object (list, tuple, iterator). + Return: + An iterable. + None if the iterable can not be used by the function. + """ + # ... Your code here ... + +def ft_filter(function_to_apply, iterable): + """Filter the result of function apply to all elements of the iterable. + Args: + function_to_apply: a function taking an iterable. + iterable: an iterable object (list, tuple, iterator). + Return: + An iterable. + None if the iterable can not be used by the function. + """ + # ... Your code here ... + +def ft_reduce(function_to_apply, iterable): + """Apply function of two arguments cumulatively. + Args: + function_to_apply: a function taking an iterable. + iterable: an iterable object (list, tuple, iterator). + Return: + A value, of same type of elements in the iterable parameter. + None if the iterable can not be used by the function. + """ + # ... Your code here ... +\end{minted} + +% ================================== % +\section*{Examples} +% ---------------------------------- % + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +# Example 1: +x = [1, 2, 3, 4, 5] +ft_map(lambda dum: dum + 1, x) +# Output: + # The adress will be different + +list(ft_map(lambda t: t + 1, x)) +# Output: +[2, 3, 4, 5, 6] + +# Example 2: +ft_filter(lambda dum: not (dum % 2), x) +# Output: + # The adress will be different + +list(ft_filter(lambda dum: not (dum % 2), x)) +# Output: +[2, 4] + +# Example 3: +lst = ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] +ft_reduce(lambda u, v: u + v, lst) +# Output: +"Hello world" +\end{minted} +\\ +You are expected to raise similar exceptions than those of +\texttt{map}, \texttt{filter} and \texttt{reduce} when wrong parameters are given (but no need +to reproduce the exact same exception messages). \ No newline at end of file diff --git a/module02/subject/exercises/m02ex01.tex b/module02/subject/exercises/m02ex01.tex new file mode 100644 index 00000000..86b00276 --- /dev/null +++ b/module02/subject/exercises/m02ex01.tex @@ -0,0 +1,92 @@ +\chapter{Exercise 01} +\extitle{args and kwargs?} +\turnindir{ex01} +\exnumber{01} +\exfiles{main.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to discover and manipulate \texttt{*args} and \texttt{**kwargs} arguments. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +In this exercise you have to implement a function named \texttt{what\_are\_the\_vars} +which returns an instance of class ObjectC.\\ +\\ +ObjectC attributes are set via the parameters received during the instanciation. +You will have to modify the 'instance' \texttt{ObjectC}, \textbf{NOT} the class.\\ +\\ +You should take a look at \texttt{getattr}, \texttt{setattr} built-in functions.\\ +\\ +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +def what_are_the_vars(...): + """ + ... + """ + # ... Your code here ... + +class ObjectC(object): + def __init__(self): + # ... Your code here ... + +def doom_printer(obj): + if obj is None: + print("ERROR") + print("end") + return + for attr in dir(obj): + if attr[0] != '_': + value = getattr(obj, attr) + print("{}: {}".format(attr, value)) + print("end") + +if __name__ == "__main__": + obj = what_are_the_vars(7) + doom_printer(obj) + obj = what_are_the_vars(None, []) + doom_printer(obj) + obj = what_are_the_vars("ft_lol", "Hi") + doom_printer(obj) + obj = what_are_the_vars() + doom_printer(obj) + obj = what_are_the_vars(12, "Yes", [0, 0, 0], a=10, hello="world") + doom_printer(obj) + obj = what_are_the_vars(42, a=10, var_0="world") + doom_printer(obj) + obj = what_are_the_vars(42, "Yes", a=10, var_2="world") + doom_printer(obj) +\end{minted} + +% ================================= % +\section*{Examples} +% --------------------------------- % + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +$> python main.py +var_0: 7 +end +var_0: None +var_1: [] +end +var_0: ft_lol +var_1: Hi +end +end +a: 10 +hello: world +var_0: 12 +var_1: Yes +var_2: [0, 0, 0] +end +ERROR +end +a: 10 +var_0: 42 +var_1: Yes +var_2: world +end +\end{minted} diff --git a/module02/subject/exercises/m02ex02.tex b/module02/subject/exercises/m02ex02.tex new file mode 100644 index 00000000..fb0fae4c --- /dev/null +++ b/module02/subject/exercises/m02ex02.tex @@ -0,0 +1,118 @@ +\chapter{Exercise 02} +\extitle{The logger} +\turnindir{ex02} +\exnumber{02} +\exfiles{logger.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +In this exercise, you will learn about decorators and we are not talking about +the decoration of your room.\\ +\\ +The \texttt{@log} will write info about the decorated function in a +\texttt{machine.log} file.\\ +\\ +% ================================= % +\section*{Instructions} +% --------------------------------- % +You have to create the log decorator in the same file.\\ +\\ +Pay attention to all the different actions logged at the call of +each method. You may notice the username from environment +variables is written to the log file.\\ +\\ + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +import time +from random import randint +import os + +#... your definition of log decorator... + +class CoffeeMachine(): + + water_level = 100 + + @log + def start_machine(self): + if self.water_level > 20: + return True + else: + print("Please add water!") + return False + + @log + def boil_water(self): + return "boiling..." + + @log + def make_coffee(self): + if self.start_machine(): + for _ in range(20): + time.sleep(0.1) + self.water_level -= 1 + print(self.boil_water()) + print("Coffee is ready!") + + @log + def add_water(self, water_level): + time.sleep(randint(1, 5)) + self.water_level += water_level + print("Blub blub blub...") + + +if __name__ == "__main__": + + machine = CoffeeMachine() + for i in range(0, 5): + machine.make_coffee() + + machine.make_coffee() + machine.add_water(70) +\end{minted} + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{42console} + $> python logger.py + boiling... + Coffee is ready! + boiling... + Coffee is ready! + boiling... + Coffee is ready! + boiling... + Coffee is ready! + Please add water! + Please add water! + Blub blub blub... + $> +\end{42console} + +\begin{42console} + $> cat machine.log + (cmaxime)Running: Start Machine [ exec-time = 0.001 ms ] + (cmaxime)Running: Boil Water [ exec-time = 0.005 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 2.499 s ] + (cmaxime)Running: Start Machine [ exec-time = 0.002 ms ] + (cmaxime)Running: Boil Water [ exec-time = 0.005 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 2.618 s ] + (cmaxime)Running: Start Machine [ exec-time = 0.003 ms ] + (cmaxime)Running: Boil Water [ exec-time = 0.004 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 2.676 s ] + (cmaxime)Running: Start Machine [ exec-time = 0.003 ms ] + (cmaxime)Running: Boil Water [ exec-time = 0.004 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 2.648 s ] + (cmaxime)Running: Start Machine [ exec-time = 0.011 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 0.029 ms ] + (cmaxime)Running: Start Machine [ exec-time = 0.009 ms ] + (cmaxime)Running: Make Coffee [ exec-time = 0.024 ms ] + (cmaxime)Running: Add Water [ exec-time = 5.026 s ] + $> +\end{42console} +Pay attention, the length between ":" and "[" is 20]. +Draw the corresponding conclusions on this part of a log entry. diff --git a/module02/subject/exercises/m02ex03.tex b/module02/subject/exercises/m02ex03.tex new file mode 100644 index 00000000..bcc11085 --- /dev/null +++ b/module02/subject/exercises/m02ex03.tex @@ -0,0 +1,100 @@ +\chapter{Exercise 03} +\extitle{Json issues} +\turnindir{ex03} +\exnumber{03} +\exfiles{csvreader.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to implement a context manager as a class.\\ +Thus you are strongly encouraged to do some preliminary research about context manager.\\ + +% ================================= % +\section*{Instructions} +% --------------------------------- % +Implement a \texttt{CsvReader} class that opens, reads, and parses a CSV file.\\ +\ +This class is then a context manager as a class.\\ +\ +In order to create it, your class requires a few built-in methods: +\begin{itemize} + \item \texttt{\_\_init\_\_}, + \item \texttt{\_\_enter\_\_}, + \item \texttt{\_\_exit\_\_}. +\end{itemize} +It is mandatory to close the file once the process is completed. +You are expected to handle properly badly-formatted CSV file (i.e. handle the exception): + +\begin{itemize} + \item mistmatch between number of fields and number of records, + \item records with different lengths. +\end{itemize} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + class CsvReader(): + def __init__(self, filename=None, sep=',', header=False, skip_top=0, skip_bottom=0): + # ... Your code here ... + + def __enter__(...): + # ... Your code here ... + + def __exit__(...): + # ... Your code here ... + + def getdata(self): + """ Retrieves the data/records from skip_top to skip bottom. + Returns: + nested list (list(list, list, ...)) representing the data. + """ + # ... Your code here ... + + def getheader(self): + """ Retrieves the header from the csv file. + Returns: + list: representing the data (when self.header is True). + None: (when self.header is False). + """ + # ... Your code here ... +\end{minted} +\newline +\texttt{CSV} (for Comma-Separated Values) files are delimited text files which use a given character to separate values.\\ +\\ +The separator (or delimiter) is usually a comma (\texttt{,}) or an hyphen comma (\texttt{;}), +but with your context manager you have to offer the possibility to change this parameter.\\ +\\ +One can decide if the class instance skips lines at the top and the bottom of the file via the +parameters \texttt{skip\_top} and \texttt{skip\_bottom}.\\ +\\ +One should also be able to keep the first line as a header if \texttt{header} is \texttt{True}.\\ +\\ +The file should not be corrupted (either a line with too many values or a line +with too few values), otherwise return \texttt{None}.\\ +\\ +You have to handle the case \texttt{file not found}.\\ +\\ +You are expected to implement two methods: +\begin{itemize} + \item \texttt{getdata()}, + \item \texttt{getheader()}. +\end{itemize} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from csvreader import CsvReader + +if __name__ == "__main__": + with CsvReader('good.csv') as file: + data = file.getdata() + header = file.getheader() +\end{minted} + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from csvreader import CsvReader + +if __name__ == "__main__": + with CsvReader('bad.csv') as file: + if file == None: + print("File is corrupted") +\end{minted} \ No newline at end of file diff --git a/module02/subject/exercises/m02ex04.tex b/module02/subject/exercises/m02ex04.tex new file mode 100644 index 00000000..a4619182 --- /dev/null +++ b/module02/subject/exercises/m02ex04.tex @@ -0,0 +1,94 @@ +\chapter{Exercise 04} +\extitle{MiniPack} +\turnindir{ex04} +\exnumber{04} +\exfiles{build.sh, *.py, *.md, *.cfg, *.txt} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to learn how to build a package and understand the magnificence of \href{https://pypi.org/}{PyPi}. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +You have to create a package called \texttt{my\_minipack}.\\ +\hint{\href{https://docs.python.org/3.9/distributing/index.html}{RTFM}} +It will have 2 \textbf{modules}: +\begin{itemize} + \item the progress bar (module00 ex10) which should be imported it via \texttt{import my\_minipack.progressbar}, + \item the logger (module02 ex02), which should be imported via \ + \texttt{import my\_minipack.logger}. +\end{itemize} +The package will be installed via pip using one of the following commands (both should work): +\begin{42console} + $> pip install ./dist/my_minipack-1.0.0.tar.gz + $> pip install ./dist/my_minipack-1.0.0-py3-none-any.whl +\end{42console} +\ +Based on the following terminal commands and corresponding outputs, draw the necessary conclusion. +\ +\begin{42console} + $> python -m venv tmp_env && source tmp_env/bin/activate + (tmp_env) > pip list + # Ouput + Package Version + ---------- ------- + pip 19.0.3 + setuptools 40.8.0 + + (tmp_env) $> cd ex04/ && bash build.sh + # Output ... No specific verbose expected, do as you wish ... + ... + (tmp_env) $> ls dist + # Output + my_minipack-1.0.0-py3-none-any.whl my_minipack-1.0.0.tar.gz + + (tmp_env) $> pip list + # Output + Package Version + ----------- ------- + my-minipack 1.0.0 + pip 21.0.1 # the last version at the time + setuptools 54.2.0 # the last version at the time + wheel 0.36.2 # the last version at the time + + (tmp_env) $> pip show -v my_minipack + # Ouput (minimum metadata asked) + Name: my-minipack + Version: 1.0.0 + Summary: Howto create a package in python. + Home-page: None + Author: mdavid + Author-email: mdavid@student.42.fr + License: GPLv3 + Location: [PATH TO BOOTCAMP PYTHON]/module02/tmp_env/lib/python3.7/site-packages + Requires: + Required-by: + Metadata-Version: 2.1 + Installer: pip + Classifiers: + Development Status :: 3 - Alpha + Intended Audience :: Developers + Intended Audience :: Students + Topic :: Education + Topic :: HowTo + Topic :: Package + License :: OSI Approved :: GNU General Public License v3 (GPLv3) + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only +(tmp_env) $> +\end{42console} +Also add a LICENSE.md (you can choose a real license or a fake one it does not matter) and a README file where you will write a small documentation about your packaged library. +\\ +The `build.sh` script upgrades `pip`, and \textbf{builds} the distribution packages in `wheel` and `egg` formats. +\\ +\info{ +You can check whether the package was properly installed by running the command \texttt{pip list} +that displays the list of installed packages and check the metadata of the package with +\texttt{pip show -v my\_minipack}. +Of course do not reproduce the exact same metadata, change the author information, modify the summary Topic and Audience items if you want to. +} \ No newline at end of file diff --git a/module02/subject/exercises/m02ex05.tex b/module02/subject/exercises/m02ex05.tex new file mode 100644 index 00000000..1ab549c3 --- /dev/null +++ b/module02/subject/exercises/m02ex05.tex @@ -0,0 +1,71 @@ +\chapter{Exercise 05} +\extitle{TinyStatistician} +\turnindir{ex05} +\exnumber{05} +\exfiles{TinyStatistician.py} +\exforbidden{Any function that calculates mean, median, quartiles, variance or standar deviation for you.} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +Initiation to very basic statistic notions. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +Create a class named \texttt{TinyStatistician} that implements the following methods: +\begin{itemize} + \item \texttt{mean(x)}: computes the mean of a given non-empty list or array \texttt{x}, using a for-loop. + The method returns the mean as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. + Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its mean is: + $$ + \mu = \frac{\sum_{i = 1}^{m}{x_i}}{m} + $$ + \item \texttt{median(x)}: computes the median of a given non-empty list or array \texttt{x}. + The method returns the median as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. + \item \texttt{quartiles(x)}: computes the $1^{\text{st}}$ and $3^{\text{rd}}$ quartiles of a given non-empty array \texttt{x}. + The method returns the quartile as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. + \item \texttt{var(x)}: computes the variance of a given non-empty list or array \texttt{x}, using a for-loop. + The method returns the variance as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. + Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its variance is: + $$ + \sigma^2 = \frac{\sum_{i = 1}^{m}{(x_i - \mu)^2}}{m} = \frac{\sum_{i = 1}^{m}{[x_i - (\frac{1}{m}\sum_{j = 1}^{m}{x_j}})]^2}{m} + $$ + \item \texttt{std(x)} : computes the standard deviation of a given non-empty list or array \texttt{x}, using a for-loop. + The method returns the standard deviation as a float, otherwise \texttt{None} if \texttt{x} is an empty list or array. + Given a vector \texttt{x} of dimension $m \times 1$, the mathematical formula of its standard deviation is: + $$ + \sigma = \sqrt{\frac{\sum_{i = 1}^{m}{(x_i - \mu)^2}}{m}} = \sqrt{\frac{\sum_{i = 1}^{m}{[x_i - (\frac{1}{m}\sum_{j = 1}^{m}{x_j}})]^2}{m}} + $$ +\end{itemize} +All methods take a \texttt{list} or a \texttt{numpy.ndarray} as parameter.\\ +\\ +We are assuming that all inputs have a correct format, i.e. a list or array of numeric type or empty list or array.\\ +\\ +You don't have to protect your functions against input errors. +\\ +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from TinyStatistician import TinyStatistician +tstat = TinyStatistician() +a = [1, 42, 300, 10, 59] + +tstat.mean(a) +# Expected result: 82.4 + +tstat.median(a) +# Expected result: 42.0 + +tstat.quartile(a) +# Expected result: [10.0, 59.0] + +tstat.var(a) +# Expected result: 12279.439999999999 + +tstat.std(a) +# Expected result: 110.81263465868862 +\end{minted} \ No newline at end of file diff --git a/module03/assets/elon_celluloid2.png b/module03/assets/elon_celluloid2.png new file mode 100644 index 00000000..1d8fb81d Binary files /dev/null and b/module03/assets/elon_celluloid2.png differ diff --git a/module03/exercises/m03ex00.tex b/module03/exercises/m03ex00.tex new file mode 100644 index 00000000..d36a7dd6 --- /dev/null +++ b/module03/exercises/m03ex00.tex @@ -0,0 +1,101 @@ +\chapter{Exercise 00} +\extitle{NumPyCreator} +\turnindir{ex00} +\exnumber{00} +\exfiles{NumPyCreator.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================== % +\section*{Objective} +% ---------------------------------- % +Introduction to the Numpy library. + +% ================================== % +\section*{Instructions} +% ---------------------------------- % +Write a class named \texttt{NumPyCreator}, that implements all of the following methods.\\ +\\ +Each method receives as an argument a different type of data structure and transforms it into a Numpy array: +\begin{itemize} + \item \texttt{from\_list(self, lst)}: takes a list or nested lists and returns its corresponding Numpy array. + \item \texttt{from\_tuple(self, tpl)}: takes a tuple or nested tuples and returns its corresponding Numpy array. + \item \texttt{from\_iterable(self, itr)}: takes an iterable and returns an array which contains all of its elements. + \item \texttt{from\_shape(self, shape, value)}: returns an array filled with the same value. + The first argument is a tuple which specifies the shape of the array, and the second argument specifies the value of the elements. + This value must be 0 by default. + \item \texttt{random(self, shape)}: returns an array filled with random values. + It takes as an argument a tuple which specifies the shape of the array. + \item \texttt{identity(self, n)}: returns an array representing the identity matrix of size n. +\end{itemize} +\textit{\textbf{BONUS:}} Add to these methods an optional argument which specifies the datatype (dtype) of the array (e.g. to represent its elements as integers, floats, ...) + +\hint{Each of these methods can be implemented in one line. You only need to find the right Numpy functions.} + +% ================================== % +\section*{Examples} +% ---------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from NumpyCreator import NumpyCreator +npc = NumpyCreator() + +npc.from_list([[1,2,3],[6,3,4]]) +# Output : +array([[1, 2, 3], + [6, 3, 4]]) + + +npc.from_list([[1,2,3],[6,4]]) +# Output : +None + + +npc.from_list([[1,2,3],['a','b','c'],[6,4,7]]) +# Output : +array([['1','2','3'], + ['a','b','c'], + ['6','4','7'], dtype='}, \texttt{\&} (or \texttt{and}). + \end{itemize} + \item \texttt{to\_grayscale}: + \begin{itemize} + \item Authorized functions: \texttt{.sum},\texttt{.shape},\texttt{.reshape},\texttt{.broadcast\_to},\texttt{.as\_type}. + \item Authorized operators: \texttt{*},\texttt{/}, \texttt{=}. + \end{itemize} +\end{itemize} +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from ImageProcessor import ImageProcessor +imp = ImageProcessor() +arr = imp.load("assets/42AI.png") +# Output : +Loading image of dimensions 200 x 200 + + +from ColorFilter import ColorFilter +cf = ColorFilter() +cf.invert(arr) + +cf.to_green(arr) + +cf.to_red(arr) + +cf.to_blue(arr) + +cf.to_celluloid(arr) + +cf.to_grayscale(arr, 'm') + +cf.to_grayscale(arr, 'weight', r_weight=0.2, 'g_weight'=0.3, 'b_weight'=0.5) +\end{minted} + +\begin{figure}[h!] + \begin{minipage}[l]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_canaGAN.png} + \vspace{-50pt} + \caption{Elon Musk} + \end{minipage} + \hfill + \begin{minipage}[c]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_inverted.png} + \vspace{-50pt} + \caption{Inverted filter} + \end{minipage} + \vspace{-20pt} + \begin{minipage}[l]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_blue.png} + \vspace{-50pt} + \caption{Blue filter} + \end{minipage} + \hfill + \begin{minipage}[c]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_green.png} + \vspace{-50pt} + \caption{Green filter} + \end{minipage} + \vspace{-20pt} + \begin{minipage}[l]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_red.png} + \vspace{-50pt} + \caption{Red filter} + \end{minipage} + \hfill + \begin{minipage}[c]{0.49\linewidth} + \includegraphics[scale=0.38]{assets/elon_celluloid.png} + \vspace{-50pt} + \caption{Celluloid filter} + \end{minipage} + +\end{figure} + +\info{ +The first image is a stylization of Elon Musk that has been generated using a style transfer algorithm implemented in our lab. +You can see the code in 42AI repository \href{https://github.com/42-AI/StyleTransferMirror}{StyleTransferMirror}} diff --git a/module03/exercises/m03ex04.tex b/module03/exercises/m03ex04.tex new file mode 100644 index 00000000..b491be61 --- /dev/null +++ b/module03/exercises/m03ex04.tex @@ -0,0 +1,134 @@ +\chapter{Exercise 04} +\extitle{K-means Clustering} +\turnindir{ex04} +\exnumber{04} +\exfiles{Kmeans.py} +\exforbidden{Any functions allowing you to perform K-Means} +\makeheaderfilesforbidden + +ALERT! DATA CORRUPTED + +% ================================= % +\section*{Objective} +% --------------------------------- % +Implementation of a basic K-means algorithm. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +The solar system census dataset is corrupted! The citizens' homelands are missing!\\ +\\ +You must implement the K-means clustering algorithm in order to recover the citizens' origins.\\ +\\ +You can find good explanations on how K-means is working here: +\href{https://en.wikipedia.org/wiki/K-means_clustering}{Wikipedia - K-Means clustering}\\ +\\ +The missing part is how to compute the distance between 2 data points (cluster centroid or a row in the data).\\ +\\ +In our case, the data we have to process is composed of 3 values (height, weight and bone\_density).\\ +\\ +Thus, each data point is a vector of 3 values.\\ +\\ +Now that we have mathematically defined our data points (vector of 3 values), it is very easy to compute the distance between two points using vector properties.\\ +You can use L1 distance, L2 distance, cosine similarity, and so forth...\\ +Choosing the distance to use is called hyperparameter tuning.\\ +\newline +I would suggest you to try with the easiest setting (L1 distance) first.\\ +\\ +What you will notice is that the final result of the "training"/"fitting" will depend a lot on the random initialization.\\ +\\ +Commonly, in machine-learning libraries, K-means is run multiple times (with different random initializations) and the best result is saved.\\ +\\ +NB: To implement the fit function, keep in mind that a centroid can be considered as the gravity center of a set of points.\\ +\\ +Your program \texttt{Kmeans.py} takes 3 parameters: \texttt{filepath}, \texttt{max\_iter} and \texttt{ncentroid}: + +\begin{42console} + python Kmeans.py filepath='../ressources/solar_system_census.csv' ncentroid=4 max_iter=30 +\end{42console} + +Your program is expected to: +\begin{itemize} + \item parse its arguments, + \item read the dataset, + \item fit the dataset, + \item display the coordinates of the different centroids and the associated region (for the case \texttt{ncentroid=4}), + \item display the number of individuals associated to each centroid, + \item (Optional) display the results on 3 differents plots, corresponding to 3 combinations of 2 parameters, using different colors to distinguish between Venus,Earth, Mars and Belt asteroids citizens. +\end{itemize} + +Create the class \texttt{KmeansClustering} with the following methods: + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +class KmeansClustering: + def __init__(self, max_iter=20, ncentroid=5): + self.ncentroid = ncentroid # number of centroids + self.max_iter = max_iter # number of max iterations to update the centroids + self.centroids = [] # values of the centroids + + def fit(self, X): + """ + Run the K-means clustering algorithm. + For the location of the initial centroids, randomly pick n centroids from the dataset. + Args: + ----- + X: has to be an numpy.ndarray, a matrice of dimension m * n. + Return: + ------- + None. + Raises: + ------- + This function should not raise any Exception. + """ + ... your code ... + + def predict(self, X): + """ + Predict from wich cluster each datapoint belongs to. + Args: + ----- + X: has to be an numpy.ndarray, a matrice of dimension m * n. + Return: + ------- + the prediction has a numpy.ndarray, a vector of dimension m * 1. + Raises: + ------- + This function should not raise any Exception. + """ + ... your code ... +\end{minted} + +% ================================= % +\section*{Dataset} +% --------------------------------- % +The dataset, named \textbf{solar\_system\_census} can be found in +the resources folder.\\ +\\ +It is a part of the solar system census dataset, and contains biometric +data such as the height, weight, and bone density of solar +system citizens.\\ +\\ +Solar citizens come from four registered areas: +\begin{itemize} + \item The flying cities of Venus, + \item United Nations of Earth, + \item Mars Republic, + \item Asteroids' Belt colonies. +\end{itemize} +Unfortunately the data about the planets of origin was lost...\\ +Use your K-means algorithm to recover it!\\ +Once your clusters are found, try to find matches between clusters and the citizens' homelands.\\ + +\hint{ + \begin{itemize} + \item People are slender on Venus than on Earth. + \item People of the Martian Republic are taller than on Earth. + \item Citizens of the Belt are the tallest of the solar system and have the lowest bone density due to the lack of gravity. + \end{itemize} +} + +% ================================= % +\section*{Examples} +% --------------------------------- % +Here is an example of the K-means algorithm in action:\\ +\url{https://i.ibb.co/bKFVVx2/ezgif-com-gif-maker.gif} \ No newline at end of file diff --git a/module03/subject/en.acknowledgements.tex b/module03/subject/en.acknowledgements.tex new file mode 100644 index 00000000..2647117e --- /dev/null +++ b/module03/subject/en.acknowledgements.tex @@ -0,0 +1,38 @@ +\section*{Contact} +% --------------------------------- % +You can contact 42AI by email: \href{mailto:contact@42ai.fr}{contact@42ai.fr}\\ +\newline +Thank you for attending 42AI's Python Bootcamp module03 ! + +% ================================= % +\section*{Acknowledgements} +% --------------------------------- % +The Python bootcamp is the result of a collective work, for which we would like to thank: +\begin{itemize} + \item Maxime Choulika (cmaxime), + \item Pierre Peigné (ppeigne, pierre@42ai.fr), + \item Matthieu David (mdavid, matthieu@42ai.fr), + \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) + \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) +\end{itemize} +who supervised the creation, the enhancement of the bootcamp and this present transcription. + +\begin{itemize} + \item Louis Develle (ldevelle, louis@42ai.fr) + \item Augustin Lopez (aulopez) + \item Luc Lenotre (llenotre) + \item Owen Roberts (oroberts) + \item Thomas Flahault (thflahau) + \item Amric Trudel (amric@42ai.fr) + \item Baptiste Lefeuvre (blefeuvr@student.42.fr) + \item Mathilde Boivin (mboivin@student.42.fr) + \item Tristan Duquesne (tduquesn@student.42.fr) +\end{itemize} +for your investment in the creation and development of these modules. + +\begin{itemize} + \item All prior participants who took a moment to provide their feedbacks, and help us improve these bootcamps ! +\end{itemize} + + \vfill +\doclicenseThis \ No newline at end of file diff --git a/module02/subject/en.py_proj.tex b/module03/subject/en.instructions.tex similarity index 50% rename from module02/subject/en.py_proj.tex rename to module03/subject/en.instructions.tex index f106e804..37463d60 100644 --- a/module02/subject/en.py_proj.tex +++ b/module03/subject/en.instructions.tex @@ -1,37 +1,25 @@ -%******************************************************************************% -% % -% Common Instructions % -% for Python Projects % -% % -%******************************************************************************% - \chapter{Common Instructions} \begin{itemize} \item The version of Python recommended to use is 3.7, you can check the version of Python with the following command: \texttt{python -V} - \item The norm: during this piscine, it is recommended to follow the + \item The norm: during this bootcamp, it is recommended to follow the \href{https://www.python.org/dev/peps/pep-0008/}{PEP 8 standards}, though it is not mandatory. You can install \href{https://pypi.org/project/pycodestyle}{pycodestyle} which is a tool to check your Python code. - \item The function \texttt{eval} is never allowed. - \item The exercises are ordered from the easiest to the hardest. - \item Your exercises are going to be evaluated by someone else, - so make sure that your variable names and function names are appropriate and civil. - + so make sure that your variable names and function names are appropriate and civil. \item Your manual is the internet. \item If you are a student from 42, you can access our Discord server on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your - questions to your peers in the dedicated Bootcamp channel. + questions to your peers in the dedicated Bootcamp channel. - \item You can also ask questions in the \texttt{\#bootcamps} channel on Slack at \href{https://42-ai.slack.com}{42AI} - or \href{42born2code.slack.com}{42born2code}. - - \item If you find any issue or mistakes in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. + \item You can learn more about 42 Artificial Intelligence by visiting \href{https://42-ai.github.io}{our website}. + + \item If you find any issue or mistake in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. \item We encourage you to create test programs for your project even though this work \textbf{won't have to be @@ -40,10 +28,9 @@ \chapter{Common Instructions} those tests especially useful during your defence. Indeed, during defence, you are free to use your tests and/or the tests of the peer you are evaluating. - - \item Submit your work to your assigned git repository. Only the work in the - git repository will be graded. If Deepthought is assigned to grade your - work, it will be run after your peer-evaluations. - If an error happens in any section of your work during Deepthought's grading, - the evaluation will stop. + + \item We are constantly looking to improve these bootcamps, and your feedbacks are essential for us to do so !\\ + You can tell us more about your experience with this module by filling \href{https://forms.gle/mBe7sBKq9tJzpDG37}{this form}.\\ + Thank you in advance and good luck for this bootcamp ! + \end{itemize} \ No newline at end of file diff --git a/module03/subject/en.subject.pdf b/module03/subject/en.subject.pdf index 73661658..aa129ce8 100644 Binary files a/module03/subject/en.subject.pdf and b/module03/subject/en.subject.pdf differ diff --git a/module03/subject/en.subject.pdf.version b/module03/subject/en.subject.pdf.version deleted file mode 100644 index 56a6051c..00000000 --- a/module03/subject/en.subject.pdf.version +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/module03/subject/en.subject.tex b/module03/subject/en.subject.tex index 7c320c46..0dbf2fc9 100644 --- a/module03/subject/en.subject.tex +++ b/module03/subject/en.subject.tex @@ -130,7 +130,7 @@ } \maketitle -\input{en.py_proj.tex} +\input{en.instructions.tex} \newpage \tableofcontents \startexercices @@ -147,854 +147,36 @@ % ============================================== % % ===========================(start ex 00) % -\chapter{Exercise 00} -\extitle{NumPyCreator} -\turnindir{ex00} -\exnumber{00} -\exfiles{NumPyCreator.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================== % -\section*{Objective} -% ---------------------------------- % -Introduction to the Numpy library. - -% ================================== % -\section*{Instructions} -% ---------------------------------- % -Write a class named \texttt{NumPyCreator}, that implements all of the following methods. - -Each method receives as an argument a different type of data structure and transforms it into a Numpy array: -\begin{itemize} - \item \texttt{from\_list(self, lst)}: takes a list or nested lists and returns its corresponding Numpy array. - \item \texttt{from\_tuple(self, tpl)}: takes a tuple or nested tuples and returns its corresponding Numpy array. - \item \texttt{from\_iterable(self, itr)}: takes an iterable and returns an array which contains all of its elements. - \item \texttt{from\_shape(self, shape, value)}: returns an array filled with the same value. - The first argument is a tuple which specifies the shape of the array, and the second argument specifies the value of the elements. - This value must be 0 by default. - \item \texttt{random(self, shape)}: returns an array filled with random values. - It takes as an argument a tuple which specifies the shape of the array. - \item \texttt{identity(self, n)}: returns an array representing the identity matrix of size n. -\end{itemize} - - -\textit{\textbf{BONUS:}} Add to these methods an optional argument which specifies the datatype (dtype) of the array (e.g. to represent its elements as integers, floats, ...) - -\hint{Each of these methods can be implemented in one line. You only need to find the right Numpy functions.} - -% ================================== % -\section*{Examples} -% ---------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from NumpyCreator import NumpyCreator -npc = NumpyCreator() - -npc.from_list([[1,2,3],[6,3,4]]) -# Output : -array([[1, 2, 3], - [6, 3, 4]]) - - -npc.from_list([[1,2,3],[6,4]]) -# Output : -None - - -npc.from_list([[1,2,3],['a','b','c'],[6,4,7]]) -# Output : -array([['1','2','3'], - ['a','b','c'], - ['6','4','7'], dtype='}, \texttt{\&} (or \texttt{and}). - \end{itemize} - \item \texttt{to\_grayscale}: - \begin{itemize} - \item Authorized functions: \texttt{.sum},\texttt{.shape},\texttt{.reshape},\texttt{.broadcast\_to},\texttt{.as\_type}. - \item Authorized operators: \texttt{*},\texttt{/}, \texttt{=}. - \end{itemize} -\end{itemize} -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from ImageProcessor import ImageProcessor -imp = ImageProcessor() -arr = imp.load("assets/42AI.png") -# Output : -Loading image of dimensions 200 x 200 - - -from ColorFilter import ColorFilter -cf = ColorFilter() -cf.invert(arr) - -cf.to_green(arr) - -cf.to_red(arr) - -cf.to_blue(arr) - -cf.to_celluloid(arr) - -cf.to_grayscale(arr, 'm') - -cf.to_grayscale(arr, 'weight', r_weight=0.2, 'g_weight'=0.3, 'b_weight'=0.5) -\end{minted} - -\begin{figure}[h!] - \begin{minipage}[l]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_canaGAN.png} - \vspace{-50pt} - \caption{Elon Musk} - \end{minipage} - \hfill - \begin{minipage}[c]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_inverted.png} - \vspace{-50pt} - \caption{Inverted filter} - \end{minipage} - \vspace{-20pt} - \begin{minipage}[l]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_blue.png} - \vspace{-50pt} - \caption{Blue filter} - \end{minipage} - \hfill - \begin{minipage}[c]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_green.png} - \vspace{-50pt} - \caption{Green filter} - \end{minipage} - \vspace{-20pt} - \begin{minipage}[l]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_red.png} - \vspace{-50pt} - \caption{Red filter} - \end{minipage} - \hfill - \begin{minipage}[c]{0.49\linewidth} - \includegraphics[scale=0.38]{assets/elon_celluloid.png} - \vspace{-50pt} - \caption{Celluloid filter} - \end{minipage} - -\end{figure} - -\info{ -The first image is a stylization of Elon Musk that has been generated using a style transfer algorithm implemented in our lab. -You can see the code in 42AI repository \href{https://github.com/42-AI/StyleTransferMirror}{StyleTransferMirror}} - +\input{exercises/m03ex03.tex} % ===========================(fin ex 03) % % ============================================== % - \newpage % ============================================== % % ===========================(start ex 04) % -\chapter{Exercise 04} -\extitle{K-means Clustering} -\turnindir{ex04} -\exnumber{04} -\exfiles{Kmeans.py} -\exforbidden{Any functions allowing you to perform K-Means} -\makeheaderfilesforbidden - -ALERT! DATA CORRUPTED - -% ================================= % -\section*{Objective} -% --------------------------------- % -Implementation of a basic K-means algorithm. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -The solar system census dataset is corrupted! The citizens' homelands are missing! - -You must implement the K-means clustering algorithm in order to recover the citizens' origins.\\ - -You can find good explanations on how K-means is working here: -\href{https://bigdata-madesimple.com/possibly-the-simplest-way-to-explain-k-means-algorithm/}{Possibly the simplest way to explain K-Means algorithm} - -The missing part is how to compute the distance between 2 data points (cluster centroid or a row in the data). - -In our case, the data we have to process is composed of 3 values (height, weight and bone\_density). - -Thus, each data point is a vector of 3 values. - -Now that we have mathematically defined our data points (vector of 3 values), it is very easy to compute the distance between two points using vector properties.\\ - -You can use L1 distance, L2 distance, cosine similarity, and so forth... - -Choosing the distance to use is called hyperparameter tuning. - -I would suggest you to try with the easiest setting (L1 distance) first.\\ - -What you will notice is that the final result of the "training"/"fitting" will depend a lot on the random initialization. - -Commonly, in machine-learning libraries, K-means is run multiple times (with different random initializations) and the best result is saved. - -NB: To implement the fit function, keep in mind that a centroid can be considered as the gravity center of a set of points. - -Your program \texttt{Kmeans.py} takes 3 parameters: \texttt{filepath}, \texttt{max\_iter} and \texttt{ncentroid}: - -\begin{42console} - python Kmeans.py filepath='../ressources/solar_system_census.csv' ncentroid=4 max_iter=30 -\end{42console} - -Your program is expected to: -\begin{itemize} - \item parse its arguments, - \item read the dataset, - \item fit the dataset, - \item display the coordinates of the different centroids and the associated region (for the case \texttt{ncentroid=4}), - \item display the number of individuals associated to each centroid, - \item (Optional) display the results on 3 differents plots, corresponding to 3 combinations of 2 parameters, using different colors to distinguish between Venus,Earth, Mars and Belt asteroids citizens. -\end{itemize} - -Create the class \texttt{KmeansClustering} with the following methods: - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -class KmeansClustering: - def __init__(self, max_iter=20, ncentroid=5): - self.ncentroid = ncentroid # number of centroids - self.max_iter = max_iter # number of max iterations to update the centroids - self.centroids = [] # values of the centroids - - def fit(self, X): - """ - Run the K-means clustering algorithm. - For the location of the initial centroids, randomly pick n centroids from the dataset. - Args: - ----- - X: has to be an numpy.ndarray, a matrice of dimension m * n. - Return: - ------- - None. - Raises: - ------- - This function should not raise any Exception. - """ - ... your code ... - - def predict(self, X): - """ - Predict from wich cluster each datapoint belongs to. - Args: - ----- - X: has to be an numpy.ndarray, a matrice of dimension m * n. - Return: - ------- - the prediction has a numpy.ndarray, a vector of dimension m * 1. - Raises: - ------- - This function should not raise any Exception. - """ - ... your code ... -\end{minted} - -% ================================= % -\section*{Dataset} -% --------------------------------- % -The dataset, named \textbf{solar\_system\_census} can be found in -the resources folder. - -It is a part of the solar system census dataset, and contains biometric -data such as the height, weight, and bone density of solar -system citizens. - -Solar citizens come from four registered areas: -\begin{itemize} - \item The flying cities of Venus, - \item United Nations of Earth, - \item Mars Republic, - \item Asteroids' Belt colonies. -\end{itemize} - -Unfortunately the data about the planets of origin was lost... -Use your K-means algorithm to recover it! -Once your clusters are found, try to find matches between clusters and the citizens' homelands. - -\hint{ - \begin{itemize} - \item People are slender on Venus than on Earth. - \item People of the Martian Republic are taller than on Earth. - \item Citizens of the Belt are the tallest of the solar system and have the lowest bone density due to the lack of gravity. - \end{itemize} -} - -% ================================= % -\section*{Examples} -% --------------------------------- % -Here is an example of the K-means algorithm in action:\\ -\url{https://i.ibb.co/bKFVVx2/ezgif-com-gif-maker.gif} - - +\input{exercises/m03ex04.tex} % ===========================(fin ex 04) % % ============================================== % - \newpage - -% ================================= % -\section*{Contact} -% --------------------------------- % -You can contact 42AI association by email: contact@42ai.fr\\ - -If you are a student from 42, you can access our Discord server -on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your -questions to your peers in the dedicated Bootcamp channel. - -Find all the relevant and up-to-date information about 42AI on \href{https://42-ai.github.io}{our Website} ! - -Thank you for attending this Python Bootcamp module03 ! % ================================= % -\section*{Acknowledgements} -% --------------------------------- % -The modules Python \& ML is the result of a collective work, we would like to thank: -\begin{itemize} - \item Maxime Choulika (cmaxime), - \item Pierre Peigné (ppeigne, pierre@42ai.fr), - \item Matthieu David (mdavid, matthieu@42ai.fr), - \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) -\end{itemize} -who supervised the creation, the enhancement and this present transcription. - -\begin{itemize} - \item Louis Develle (ldevelle, louis@42ai.fr) - \item Augustin Lopez (aulopez) - \item Luc Lenotre (llenotre) - \item Owen Roberts (oroberts) - \item Thomas Flahault (thflahau) - \item Amric Trudel (amric@42ai.fr) - \item Baptiste Lefeuvre (blefeuvr@student.42.fr) - \item Mathilde Boivin (mboivin@student.42.fr) - \item Tristan Duquesne (tduquesn@student.42.fr) -\end{itemize} -for your investment for the creation and development of these modules. - -\begin{itemize} - \item Barthélémy Leveque (bleveque@student.42.fr) - \item Remy Oster (roster@student.42.fr) - \item Quentin Bragard (qbragard@student.42.fr) - \item Marie Dufourq (madufour@student.42.fr) - \item Adrien Vardon (advardon@student.42.fr) -\end{itemize} -who betatest the first version of the modules of Machine Learning. -\vfill -\doclicenseThis +\input{en.acknowledgements.tex} \end{document} \ No newline at end of file diff --git a/module04/exercises/m04ex00.tex b/module04/exercises/m04ex00.tex new file mode 100644 index 00000000..58f5e5fd --- /dev/null +++ b/module04/exercises/m04ex00.tex @@ -0,0 +1,59 @@ +\chapter{Exercise 00} +\extitle{FileLoader} +\turnindir{ex00} +\exnumber{00} +\exfiles{FileLoader.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================== % +\section*{Objective} +% ---------------------------------- % +The goal of this exercise is to create a Fileloader class containing a +load and a display method. + +% ================================== % +\section*{Instructions} +% ---------------------------------- % +Write a class named \texttt{FileLoader} which implements the following methods: +\begin{itemize} + \item \texttt{load(self, path)}: takes as an argument the file path of the dataset to load, + displays a message specifying the dimensions of the dataset (e.g. 340 x 500) + and returns the dataset loaded as a pandas.DataFrame. + \item \texttt{display(self, df, n)}: takes a pandas.DataFrame and an integer as arguments, + displays the first n rows of the dataset if n is positive, or the last n rows if n is negative. +\end{itemize} + + +\noindent \texttt{FileLoader} object should not raise any exceptions (wrong path, file does not exist, parameters different than a string ...). +% ================================== % +\section*{Examples} +% ---------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load("../data/adult_data.csv") +# Output +Loading dataset of dimensions 32561 x 15 + + +loader.display(data, 12) +# Output +age workclass fnlwgt ... hours-per-week native-country salary +0 39 State-gov 77516 ... 40 United-States <=50K +1 50 Self-emp-not-inc 83311 ... 13 United-States <=50K +2 38 Private 215646 ... 40 United-States <=50K +3 53 Private 234721 ... 40 United-States <=50K +4 28 Private 338409 ... 40 Cuba <=50K +5 37 Private 284582 ... 40 United-States <=50K +6 49 Private 160187 ... 16 Jamaica <=50K +7 52 Self-emp-not-inc 209642 ... 45 United-States >50K +8 31 Private 45781 ... 50 United-States >50K +9 42 Private 159449 ... 40 United-States >50K +10 37 Private 280464 ... 80 United-States >50K +11 30 State-gov 141297 ... 40 India >50K + +[12 rows x 15 columns] +\end{minted} + +\hint{NB: Your terminal may display more columns if the window is wider.} \ No newline at end of file diff --git a/module04/exercises/m04ex01.tex b/module04/exercises/m04ex01.tex new file mode 100644 index 00000000..3dd950e2 --- /dev/null +++ b/module04/exercises/m04ex01.tex @@ -0,0 +1,45 @@ +\chapter{Exercise 01} +\extitle{YoungestFellah} +\turnindir{ex01} +\exnumber{01} +\exfiles{FileLoader.py, YoungestFellah.py} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to create a function that will return a +dictionary containing the age of the youngest woman and the youngest +man who took part in the Olympics for a given year. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the following dataset: \texttt{athlete\_events.csv}.\\ +\\ +Write a function \texttt{youngest\_fellah} that takes two arguments: +\begin{itemize} + \item a pandas.DataFrame which contains the dataset + \item an Olympic year. +\end{itemize} +The function returns a dictionary containing the age of the youngest +woman and man who took part in the Olympics on that year. +The names of the dictionary's keys are up to you, but they must be explicit and self-explanatory. + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load('../data/athlete_events.csv') +# Output +Loading dataset of dimensions 271116 x 15 + +from YoungestFellah import youngest_fellah +youngest_fellah(data, 2004) +# Output +{'f': 13.0, 'm': 14.0} +\end{minted} diff --git a/module04/exercises/m04ex02.tex b/module04/exercises/m04ex02.tex new file mode 100644 index 00000000..7c4bc52f --- /dev/null +++ b/module04/exercises/m04ex02.tex @@ -0,0 +1,58 @@ +\chapter{Exercise 02} +\extitle{ProportionBySport} +\turnindir{ex02} +\exnumber{02} +\exfiles{FileLoader.py, ProportionBySport.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to create a function displaying +the proportion of participants who played a given sport, among +the participants of a given gender. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the dataset \texttt{athlete\_events.csv}. + +Write a function \texttt{proportion\_by\_sport} that takes four arguments: +\begin{itemize} + \item a pandas.DataFrame of the dataset, + \item an olympic year, + \item a sport, + \item a gender. +\end{itemize} +The function returns a float corresponding to the proportion (percentage) of participants +who played the given sport among the participants of the given gender.\\ +\\ +The function answers questions like the following : +"What was the percentage of female basketball players among all female +participants in the 2016 Olympics?" + +\hint{ +Here and later on, if needed, drop duplicate sports people to count only unique ones. Beware to call the dropping function +at the right moment and with the right parameters, in order not to omit any individual. +} + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load('../data/athlete_events.csv') +# Output +Loading dataset of dimensions 271116 x 15 + + +from ProportionBySport import proportion_by_sport +proportion_by_sport(data, 2004, 'Tennis', 'F') +# Output +0.019302325581395347 +\end{minted} +\newline +We assume that we are always using valid arguments as input, +and thus do not need to handle input errors. \ No newline at end of file diff --git a/module04/exercises/m04ex03.tex b/module04/exercises/m04ex03.tex new file mode 100644 index 00000000..4735b749 --- /dev/null +++ b/module04/exercises/m04ex03.tex @@ -0,0 +1,56 @@ +\chapter{Exercise 03} +\extitle{HowManyMedals} +\turnindir{ex03} +\exnumber{03} +\exfiles{FileLoader.py, HowManyMedals.py} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to implement a function that will return +a dictionary of dictionaries giving the number and types of medals +for each year during which the participant won medals. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the following dataset: \texttt{athlete\_events.csv}. + + +Write a function \texttt{how\_many\_medals} that takes two arguments: +\begin{itemize} + \item a pandas.DataFrame which contains the dataset, + \item a participant's name. +\end{itemize} +The function returns a dictionary of dictionaries giving the number and type of medals +for each year during which the participant won medals.\\ +\\ +The keys of the main dictionary are the years of the Olympic games.\\ +\\ +In each year's dictionary, the keys are 'G', 'S', 'B' corresponding to the type of +medals won (Gold, Silver, Bronze).\ +The innermost values correspond to the number of medals of a given type won for a given year. + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load('../data/athlete_events.csv') +# Output +Loading dataset of dimensions 271116 x 15 + + +from HowManyMedals import how_many_medals +how_many_medals(data, 'Kjetil Andr Aamodt') +# Output +{1992: {'G': 1, 'S': 0, 'B': 1}, + 1994: {'G': 0, 'S': 2, 'B': 1}, + 1998: {'G': 0, 'S': 0, 'B': 0}, + 2002: {'G': 2, 'S': 0, 'B': 0}, + 2006: {'G': 1, 'S': 0, 'B': 0}} +\end{minted} \ No newline at end of file diff --git a/module04/exercises/m04ex04.tex b/module04/exercises/m04ex04.tex new file mode 100644 index 00000000..aab0f34b --- /dev/null +++ b/module04/exercises/m04ex04.tex @@ -0,0 +1,62 @@ +\chapter{Exercise 04} +\extitle{SpatioTemporalData} +\turnindir{ex04} +\exnumber{04} +\exfiles{FileLoader.py, SpatioTemporalData.py} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to implement a class called \texttt{SpatioTemporalData} +that takes a dataset (pandas.DataFrame) as argument in its constructor +and implements two methods. +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the dataset \texttt{athlete\_events.csv}.\\ +\\ +Write a class called \texttt{SpatioTemporalData} that takes a dataset +(pandas.DataFrame) as argument in its constructor and implements the +following methods: +\begin{itemize} + \item \texttt{when(location)}: takes a location as an argument and returns + a list containing the years where games were held in the given location, + \item \texttt{where(date)}: takes a date as an argument and returns the location + where the Olympics took place in the given year. +\end{itemize} + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load('../data/athlete_events.csv') +# Output +Loading dataset of dimensions 271116 x 15 + + +from SpatioTemporalData import SpatioTemporalData +sp = SpatioTemporalData(data) +sp.where(1896) +# Output +['Athina'] + + +sp.where(2016) +# Output +['Rio de Janeiro'] + + +sp.when('Athina') +# Output +[2004, 1906, 1896] + + +sp.when('Paris') +# Output +[1900, 1924] +\end{minted} \ No newline at end of file diff --git a/module04/exercises/m04ex05.tex b/module04/exercises/m04ex05.tex new file mode 100644 index 00000000..cec70979 --- /dev/null +++ b/module04/exercises/m04ex05.tex @@ -0,0 +1,70 @@ +\chapter{Exercise 05} +\extitle{HowManyMedalsByCountry} +\turnindir{ex05} +\exnumber{05} +\exfiles{FileLoader.py, HowManyMedalsByCountry.py} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to write a function that returns a +dictionary of dictionaries giving the number and types of medals for +each competition where a given country delegation earned medals. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the following dataset: \texttt{athlete\_events.csv}\\ +\\ +Write a function \texttt{how\_many\_medals\_by\_country} that takes two arguments: +\begin{itemize} + \item a pandas.DataFrame which contains the dataset + \item a country name. +\end{itemize} +The function returns a dictionary of dictionaries giving the number and +types of medals for each competition where the country delegation earned medals.\\ +\\ +The keys of the main dictionary are the Olympic games' years. In each +year's dictionary, the keys are 'G', 'S', 'B' corresponding to the +types of medals won. +\\ +Duplicated medals per team games should be handled and not counted twice.\\ +\\ +Hint: You may find this list to be of some use. + +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} + team_sports = ['Basketball', 'Football', 'Tug-Of-War', 'Badminton', 'Sailing', + 'Handball', 'Water Polo', 'Hockey', 'Rowing', 'Bobsleigh', 'Softball', + 'Volleyball', 'Synchronized Swimming', 'Baseball', 'Rugby Sevens', + 'Rugby', 'Lacrosse', 'Polo'] +\end{minted} + +% ================================= % +\section*{Examples} +% --------------------------------- % +\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} +from FileLoader import FileLoader +loader = FileLoader() +data = loader.load('../data/athlete_events.csv') +# Output +Loading dataset of dimensions 271116 x 15 + + +from HowManyMedalsByCountry import how_many_medals_by_country +how_many_medals_by_country(data, 'Martian Federation') +# Output +{2192: {'G': 17, 'S': 14, 'B': 23}, 2196: {'G': 8, 'S': 21, 'B': 19}, 2200: {'G': 26, 'S': 19, 'B': 7}} +\end{minted} +\newline +You probably guessed by now that we gave up providing real examples...\\ +\\ +If you want real examples, you can easily look online.\\ +\\ +Do beware that some medals might be awarded or removed years after the games +are over, for example if a previous medallist was found to have cheated.\\ +\\ +The \texttt{athlete\_events.csv} dataset might not always take these posterior +changes into account. \ No newline at end of file diff --git a/module04/exercises/m04ex06.tex b/module04/exercises/m04ex06.tex new file mode 100644 index 00000000..49c43ea0 --- /dev/null +++ b/module04/exercises/m04ex06.tex @@ -0,0 +1,62 @@ +\chapter{Exercise 06} +\extitle{MyPlotLib} +\turnindir{ex06} +\exnumber{06} +\exfiles{MyPlotLib.py} +\exforbidden{None} +\makeheaderfilesforbidden + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to introduce you to plotting methods using different +libraries like Pandas, Matplotlib, Seaborn or Scipy. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the following dataset: \texttt{athlete\_events.csv}\\ +\\ +Write a class called \texttt{MyPlotLib}. This class implements different plotting +methods, each of which takes two arguments: +\begin{itemize} + \item a pandas.DataFrame which contains the dataset, + \item a list of features names. +\end{itemize} + +\hint{\href{https://towardsdatascience.com/feature-engineering-for-machine-learning-3a5e293a5114}{What is a feature?}} + +\begin{itemize} + \item \texttt{histogram(data, features)}: plots one histogram for each numerical feature in the list, + \item \texttt{density(data, features)}: plots the density curve of each numerical feature in the list, + \item \texttt{pair\_plot(data, features)}: plots a matrix of subplots (also called scatter plot matrix). + On each subplot shows a scatter plot of one numerical variable against another one. + The main diagonal of this matrix shows simple histograms. + \item \texttt{box\_plot(data, features)}: displays a box plot for each numerical variable in the dataset. +\end{itemize} + +% ================================= % +\section*{Examples} +% --------------------------------- % + +\begin{figure}[h!] + \begin{minipage}[l]{0.49\linewidth} + \includegraphics[scale=0.39]{assets/ex06_histogram.png} + \caption{histogram} + \end{minipage} + \hfill + \begin{minipage}[c]{0.49\linewidth} + \includegraphics[scale=0.39]{assets/ex06_density.png} + \caption{density} + \end{minipage} + + \begin{minipage}[l]{0.49\linewidth} + \includegraphics[scale=0.39]{assets/ex06_pair_plot.png} + \caption{pair plot} + \end{minipage} + \hfill + \begin{minipage}[c]{0.49\linewidth} + \includegraphics[scale=0.39]{assets/ex06_box_plot.png} + \caption{box plot} + \end{minipage} +\end{figure} \ No newline at end of file diff --git a/module04/exercises/m04ex07.tex b/module04/exercises/m04ex07.tex new file mode 100644 index 00000000..3b6731d8 --- /dev/null +++ b/module04/exercises/m04ex07.tex @@ -0,0 +1,36 @@ +\chapter{Exercise 07} +\extitle{Komparator} +\turnindir{ex07} +\exnumber{07} +\exfiles{Komparator.py, MyPlotLib.py (optional)} +\exforbidden{None} +\makeheaderfilesforbidden + + +% ================================= % +\section*{Objective} +% --------------------------------- % +The goal of this exercise is to introduce plotting methods among the different +libraries Pandas, Matplotlib, Seaborn or Scipy. + +% ================================= % +\section*{Instructions} +% --------------------------------- % +This exercise uses the following dataset: \texttt{athlete\_events.csv}.\\ +\\ +Write a class called \texttt{Komparator} whose constructor takes as an argument a pandas.DataFrame which contains the dataset.\\ +\\ +The class must implement the following methods, which take as input two variable names: +\begin{itemize} + \item \texttt{compare\_box\_plots(self, categorical\_var, numerical\_var)}: displays a series of box plots + to compare how the distribution of the numerical variable changes if we only consider + the subpopulation which belongs to each category. + There should be as many box plots as categories. + For example, with Sex and Height, we would compare + the height distributions of men vs. women with two box plots. + \item \texttt{density(self, categorical\_var, numerical\_var)}: displays the density of the numerical variable. + Each subpopulation should be represented by a separate curve on the graph. + \item \texttt{compare\_histograms(self, categorical\_var, numerical\_var)}: plots the numerical variable in a separate histogram for each category. + As an extra, you can use overlapping histograms with a color code. +\end{itemize} +BONUS: Your functions can also accept a list of numerical variables (instead of just one), and output a comparison plot for each variable in the list. diff --git a/module04/subject/en.acknowledgements.tex b/module04/subject/en.acknowledgements.tex new file mode 100644 index 00000000..ac0f036e --- /dev/null +++ b/module04/subject/en.acknowledgements.tex @@ -0,0 +1,38 @@ +\section*{Contact} +% --------------------------------- % +You can contact 42AI by email: \href{mailto:contact@42ai.fr}{contact@42ai.fr}\\ +\newline +Thank you for attending 42AI's Python Bootcamp module04 ! + +% ================================= % +\section*{Acknowledgements} +% --------------------------------- % +The Python bootcamp is the result of a collective work, for which we would like to thank: +\begin{itemize} + \item Maxime Choulika (cmaxime), + \item Pierre Peigné (ppeigne, pierre@42ai.fr), + \item Matthieu David (mdavid, matthieu@42ai.fr), + \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) + \item Mathieu Perez (maperez, mathieu.perez@42ai.fr) +\end{itemize} +who supervised the creation, the enhancement of the bootcamp and this present transcription. + +\begin{itemize} + \item Louis Develle (ldevelle, louis@42ai.fr) + \item Augustin Lopez (aulopez) + \item Luc Lenotre (llenotre) + \item Owen Roberts (oroberts) + \item Thomas Flahault (thflahau) + \item Amric Trudel (amric@42ai.fr) + \item Baptiste Lefeuvre (blefeuvr@student.42.fr) + \item Mathilde Boivin (mboivin@student.42.fr) + \item Tristan Duquesne (tduquesn@student.42.fr) +\end{itemize} +for your investment in the creation and development of these modules. + +\begin{itemize} + \item All prior participants who took a moment to provide their feedbacks, and help us improve these bootcamps ! +\end{itemize} + +\vfill +\doclicenseThis \ No newline at end of file diff --git a/module04/subject/en.instructions.tex b/module04/subject/en.instructions.tex new file mode 100644 index 00000000..168272a9 --- /dev/null +++ b/module04/subject/en.instructions.tex @@ -0,0 +1,36 @@ +\chapter{Common Instructions} +\begin{itemize} + \item The version of Python recommended to use is 3.7, you can + check the version of Python with the following command: \texttt{python -V} + + \item The norm: during this bootcamp, it is recommended to follow the + \href{https://www.python.org/dev/peps/pep-0008/}{PEP 8 standards}, though it is not mandatory. + You can install \href{https://pypi.org/project/pycodestyle}{pycodestyle} which + is a tool to check your Python code. + \item The function \texttt{eval} is never allowed. + \item The exercises are ordered from the easiest to the hardest. + \item Your exercises are going to be evaluated by someone else, + so make sure that your variable names and function names are appropriate and civil. + \item Your manual is the internet. + + \item If you are a student from 42, you can access our Discord server + on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your + questions to your peers in the dedicated Bootcamp channel. + + \item You can learn more about 42 Artificial Intelligence by visiting \href{https://42-ai.github.io}{our website}. + + \item If you find any issue or mistake in the subject please create an issue on \href{https://github.com/42-AI/bootcamp_python/issues}{42AI repository on Github}. + + \item We encourage you to create test programs for your + project even though this work \textbf{won't have to be + submitted and won't be graded}. It will give you a chance + to easily test your work and your peers’ work. You will find + those tests especially useful during your defence. Indeed, + during defence, you are free to use your tests and/or the + tests of the peer you are evaluating. + + \item We are constantly looking to improve these bootcamps, and your feedbacks are essential for us to do so !\\ + You can tell us more about your experience with this module by filling \href{https://forms.gle/XCTac2mWnm7LAYhGA}{this form}.\\ + Thank you in advance and good luck for this bootcamp ! + +\end{itemize} \ No newline at end of file diff --git a/module04/subject/en.subject.aux b/module04/subject/en.subject.aux deleted file mode 100644 index b6401217..00000000 --- a/module04/subject/en.subject.aux +++ /dev/null @@ -1,2 +0,0 @@ -\relax -\gdef \@abspage@last{1} diff --git a/module04/subject/en.subject.fdb_latexmk b/module04/subject/en.subject.fdb_latexmk deleted file mode 100644 index 0c15b03d..00000000 --- a/module04/subject/en.subject.fdb_latexmk +++ /dev/null @@ -1,15 +0,0 @@ -# Fdb version 4 -["pdflatex"] 1727450562.40878 "/home/gh0st/Bureau/ci_cd_exp/module04/subject/en.subject.tex" "en.subject.pdf" "en.subject" 1727450562.60512 2 - "/etc/texmf/web2c/texmf.cnf" 1727339314.10574 475 c0e671620eb5563b2130f56340a5fde8 "" - "/home/gh0st/Bureau/ci_cd_exp/module04/subject/en.subject.tex" 1727450562.17309 24187 11e6bfa9cea8d658754230bc4328d019 "" - "/usr/share/texlive/texmf-dist/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/usr/share/texmf/web2c/texmf.cnf" 1707919699 40399 f2c302f7d2af602abb742093540a5834 "" - "/var/lib/texmf/web2c/pdftex/pdflatex.fmt" 1727356375 8215269 fd93dc40f384268405c8bca19f4d73c2 "" - "42-en.cls" 0 -1 0 "" - "en.subject.aux" 1727450562.40709 32 3985256e7290058c681f74d7a3565a19 "pdflatex" - "en.subject.tex" 1727450562.17309 24187 11e6bfa9cea8d658754230bc4328d019 "" - (generated) - "en.subject.aux" - "en.subject.log" - "en.subject.pdf" - (rewritten before read) diff --git a/module04/subject/en.subject.fls b/module04/subject/en.subject.fls deleted file mode 100644 index 2d99b1d6..00000000 --- a/module04/subject/en.subject.fls +++ /dev/null @@ -1,7 +0,0 @@ -PWD /home/gh0st/Bureau/ci_cd_exp/module04/subject -INPUT /etc/texmf/web2c/texmf.cnf -INPUT /usr/share/texmf/web2c/texmf.cnf -INPUT /usr/share/texlive/texmf-dist/web2c/texmf.cnf -INPUT /var/lib/texmf/web2c/pdftex/pdflatex.fmt -INPUT /home/gh0st/Bureau/ci_cd_exp/module04/subject/en.subject.tex -OUTPUT en.subject.log diff --git a/module04/subject/en.subject.pdf b/module04/subject/en.subject.pdf index 0f7e70a5..7fb0ef71 100644 Binary files a/module04/subject/en.subject.pdf and b/module04/subject/en.subject.pdf differ diff --git a/module04/subject/en.subject.pdf.version b/module04/subject/en.subject.pdf.version deleted file mode 100644 index 56a6051c..00000000 --- a/module04/subject/en.subject.pdf.version +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/module04/subject/en.subject.tex b/module04/subject/en.subject.tex index 3b8670e4..c01b431d 100644 --- a/module04/subject/en.subject.tex +++ b/module04/subject/en.subject.tex @@ -129,7 +129,7 @@ to manipulate gigantic amounts of data: Pandas. } \maketitle -\input{en.py_proj.tex} +\input{en.instructions.tex} \newpage \tableofcontents \startexercices @@ -146,577 +146,51 @@ % ============================================== % % ===========================(start ex 00) % -\chapter{Exercise 00} -\extitle{FileLoader} -\turnindir{ex00} -\exnumber{00} -\exfiles{FileLoader.py} -\exforbidden{None} -\makeheaderfilesforbidden - -% ================================== % -\section*{Objective} -% ---------------------------------- % -The goal of this exercise is to create a Fileloader class containing a -load and a display method. - -% ================================== % -\section*{Instructions} -% ---------------------------------- % -Write a class named \texttt{FileLoader} which implements the following methods: -\begin{itemize} - \item \texttt{load(self, path)}: takes as an argument the file path of the dataset to load, - displays a message specifying the dimensions of the dataset (e.g. 340 x 500) - and returns the dataset loaded as a pandas.DataFrame. - \item \texttt{display(self, df, n)}: takes a pandas.DataFrame and an integer as arguments, - displays the first n rows of the dataset if n is positive, or the last n rows if n is negative. -\end{itemize} - - -\noindent \texttt{FileLoader} object should not raise any exceptions (wrong path, file does not exist, parameters different than a string ...). -% ================================== % -\section*{Examples} -% ---------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load("../data/adult_data.csv") -# Output -Loading dataset of dimensions 32561 x 15 - - -loader.display(data, 12) -# Output -age workclass fnlwgt ... hours-per-week native-country salary -0 39 State-gov 77516 ... 40 United-States <=50K -1 50 Self-emp-not-inc 83311 ... 13 United-States <=50K -2 38 Private 215646 ... 40 United-States <=50K -3 53 Private 234721 ... 40 United-States <=50K -4 28 Private 338409 ... 40 Cuba <=50K -5 37 Private 284582 ... 40 United-States <=50K -6 49 Private 160187 ... 16 Jamaica <=50K -7 52 Self-emp-not-inc 209642 ... 45 United-States >50K -8 31 Private 45781 ... 50 United-States >50K -9 42 Private 159449 ... 40 United-States >50K -10 37 Private 280464 ... 80 United-States >50K -11 30 State-gov 141297 ... 40 India >50K - -[12 rows x 15 columns] -\end{minted} - -\hint{NB: Your terminal may display more columns if the window is wider.} - +\input{exercises/m04ex00.tex} % ===========================(fin ex 00) % % ============================================== % \newpage - % ============================================== % % ===========================(start ex 01) % -\chapter{Exercise 01} -\extitle{YoungestFellah} -\turnindir{ex01} -\exnumber{01} -\exfiles{FileLoader.py, YoungestFellah.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to create a function that will return a -dictionary containing the age of the youngest woman and the youngest -man who took part in the Olympics for a given year. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the following dataset: \texttt{athlete\_events.csv}. - -Write a function \texttt{youngest\_fellah} that takes two arguments: -\begin{itemize} - \item a pandas.DataFrame which contains the dataset - \item an Olympic year. -\end{itemize} - -The function returns a dictionary containing the age of the youngest -woman and man who took part in the Olympics on that year. -The names of the dictionary's keys are up to you, but they must be explicit and self-explanatory. - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load('../data/athlete_events.csv') -# Output -Loading dataset of dimensions 271116 x 15 - -from YoungestFellah import youngest_fellah -youngest_fellah(data, 2004) -# Output -{'f': 13.0, 'm': 14.0} -\end{minted} - - +\input{exercises/m04ex01.tex} % ===========================(fin ex 01) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 02) % -\chapter{Exercise 02} -\extitle{ProportionBySport} -\turnindir{ex02} -\exnumber{02} -\exfiles{FileLoader.py, ProportionBySport.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to create a function displaying -the proportion of participants who played a given sport, among -the participants of a given gender. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the dataset \texttt{athlete\_events.csv}. - -Write a function \texttt{proportion\_by\_sport} that takes four arguments: -\begin{itemize} - \item a pandas.DataFrame of the dataset, - \item an olympic year, - \item a sport, - \item a gender. -\end{itemize} - -The function returns a float corresponding to the proportion (percentage) of participants -who played the given sport among the participants of the given gender. - -The function answers questions like the following : -"What was the percentage of female basketball players among all female -participants in the 2016 Olympics?" - -\hint{ -Here and later on, if needed, drop duplicate sports people to count only unique ones. Beware to call the dropping function -at the right moment and with the right parameters, in order not to omit any individual. -} - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load('../data/athlete_events.csv') -# Output -Loading dataset of dimensions 271116 x 15 - - -from ProportionBySport import proportion_by_sport -proportion_by_sport(data, 2004, 'Tennis', 'F') -# Output -0.019302325581395347 -\end{minted} - -We assume that we are always using valid arguments as input, -and thus do not need to handle input errors. - +\input{exercises/m04ex02.tex} % ===========================(fin ex 02) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 03) % -\chapter{Exercise 03} -\extitle{HowManyMedals} -\turnindir{ex03} -\exnumber{03} -\exfiles{FileLoader.py, HowManyMedals.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to implement a function that will return -a dictionary of dictionaries giving the number and types of medals -for each year during which the participant won medals. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the following dataset: \texttt{athlete\_events.csv}. - - -Write a function \texttt{how\_many\_medals} that takes two arguments: -\begin{itemize} - \item a pandas.DataFrame which contains the dataset, - \item a participant's name. -\end{itemize} - -The function returns a dictionary of dictionaries giving the number and type of medals -for each year during which the participant won medals. - -The keys of the main dictionary are the years of the Olympic games. - -In each year's dictionary, the keys are 'G', 'S', 'B' corresponding to the type of -medals won (Gold, Silver, Bronze). - -The innermost values correspond to the number of medals of a given type won for a given year. - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load('../data/athlete_events.csv') -# Output -Loading dataset of dimensions 271116 x 15 - - -from HowManyMedals import how_many_medals -how_many_medals(data, 'Kjetil Andr Aamodt') -# Output -{1992: {'G': 1, 'S': 0, 'B': 1}, - 1994: {'G': 0, 'S': 2, 'B': 1}, - 1998: {'G': 0, 'S': 0, 'B': 0}, - 2002: {'G': 2, 'S': 0, 'B': 0}, - 2006: {'G': 1, 'S': 0, 'B': 0}} -\end{minted} - +\input{exercises/m04ex03.tex} % ===========================(fin ex 03) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 04) % -\chapter{Exercise 04} -\extitle{SpatioTemporalData} -\turnindir{ex04} -\exnumber{04} -\exfiles{FileLoader.py, SpatioTemporalData.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to implement a class called \texttt{SpatioTemporalData} -that takes a dataset (pandas.DataFrame) as argument in its constructor -and implements two methods. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the dataset \texttt{athlete\_events.csv}. - - -Write a class called \texttt{SpatioTemporalData} that takes a dataset -(pandas.DataFrame) as argument in its constructor and implements the -following methods: -\begin{itemize} - \item \texttt{when(location)}: takes a location as an argument and returns - a list containing the years where games were held in the given location, - \item \texttt{where(date)}: takes a date as an argument and returns the location - where the Olympics took place in the given year. -\end{itemize} - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load('../data/athlete_events.csv') -# Output -Loading dataset of dimensions 271116 x 15 - - -from SpatioTemporalData import SpatioTemporalData -sp = SpatioTemporalData(data) -sp.where(1896) -# Output -['Athina'] - - -sp.where(2016) -# Output -['Rio de Janeiro'] - - -sp.when('Athina') -# Output -[2004, 1906, 1896] - - -sp.when('Paris') -# Output -[1900, 1924] -\end{minted} - - +\input{exercises/m04ex04.tex} % ===========================(fin ex 04) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 05) % -\chapter{Exercise 05} -\extitle{HowManyMedalsByCountry} -\turnindir{ex05} -\exnumber{05} -\exfiles{FileLoader.py, HowManyMedalsByCountry.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to write a function that returns a -dictionary of dictionaries giving the number and types of medals for -each competition where a given country delegation earned medals. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the following dataset: \texttt{athlete\_events.csv} - -Write a function \texttt{how\_many\_medals\_by\_country} that takes two arguments: -\begin{itemize} - \item a pandas.DataFrame which contains the dataset - \item a country name. -\end{itemize} - -The function returns a dictionary of dictionaries giving the number and -types of medals for each competition where the country delegation earned medals. - -The keys of the main dictionary are the Olympic games' years. In each -year's dictionary, the keys are 'G', 'S', 'B' corresponding to the -types of medals won. - -Duplicated medals per team games should be handled and not counted twice. - -Hint: You may find this list to be of some use. - -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} - team_sports = ['Basketball', 'Football', 'Tug-Of-War', 'Badminton', 'Sailing', - 'Handball', 'Water Polo', 'Hockey', 'Rowing', 'Bobsleigh', 'Softball', - 'Volleyball', 'Synchronized Swimming', 'Baseball', 'Rugby Sevens', - 'Rugby', 'Lacrosse', 'Polo'] -\end{minted} - -% ================================= % -\section*{Examples} -% --------------------------------- % -\begin{minted}[bgcolor=darcula-back,formatcom=\color{lightgrey},fontsize=\scriptsize]{python} -from FileLoader import FileLoader -loader = FileLoader() -data = loader.load('../data/athlete_events.csv') -# Output -Loading dataset of dimensions 271116 x 15 - - -from HowManyMedalsByCountry import how_many_medals_by_country -how_many_medals_by_country(data, 'Martian Federation') -# Output -{2192: {'G': 17, 'S': 14, 'B': 23}, 2196: {'G': 8, 'S': 21, 'B': 19}, 2200: {'G': 26, 'S': 19, 'B': 7}} -\end{minted} - -You probably guessed by now that we gave up providing real examples... - -If you want real examples, you can easily look online. - -Do beware that some medals might be awarded or removed years after the games -are over, for example if a previous medallist was found to have cheated. - -The \texttt{athlete\_events.csv} dataset might not always take these posterior -changes into account. - +\input{exercises/m04ex05.tex} % ===========================(fin ex 05) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 06) % -\chapter{Exercise 06} -\extitle{MyPlotLib} -\turnindir{ex06} -\exnumber{06} -\exfiles{MyPlotLib.py} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to introduce you to plotting methods using different -libraries like Pandas, Matplotlib, Seaborn or Scipy. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the following dataset: \texttt{athlete\_events.csv} - -Write a class called \texttt{MyPlotLib}. This class implements different plotting -methods, each of which takes two arguments: -\begin{itemize} - \item a pandas.DataFrame which contains the dataset, - \item a list of features names. -\end{itemize} - -\hint{ - What is a feature? https://towardsdatascience.com/feature-engineering-for-machine-learning-3a5e293a5114 -} - -\begin{itemize} - \item \texttt{histogram(data, features)}: plots one histogram for each numerical feature in the list, - \item \texttt{density(data, features)}: plots the density curve of each numerical feature in the list, - \item \texttt{pair\_plot(data, features)}: plots a matrix of subplots (also called scatter plot matrix). - On each subplot shows a scatter plot of one numerical variable against another one. - The main diagonal of this matrix shows simple histograms. - \item \texttt{box\_plot(data, features)}: displays a box plot for each numerical variable in the dataset. -\end{itemize} - -% ================================= % -\section*{Examples} -% --------------------------------- % - -\begin{figure}[h!] - \begin{minipage}[l]{0.49\linewidth} - \includegraphics[scale=0.39]{assets/ex06_histogram.png} - \caption{histogram} - \end{minipage} - \hfill - \begin{minipage}[c]{0.49\linewidth} - \includegraphics[scale=0.39]{assets/ex06_density.png} - \caption{density} - \end{minipage} - - \begin{minipage}[l]{0.49\linewidth} - \includegraphics[scale=0.39]{assets/ex06_pair_plot.png} - \caption{pair plot} - \end{minipage} - \hfill - \begin{minipage}[c]{0.49\linewidth} - \includegraphics[scale=0.39]{assets/ex06_box_plot.png} - \caption{box plot} - \end{minipage} -\end{figure} - - +\input{exercises/m04ex06.tex} % ===========================(fin ex 06) % % ============================================== % - \newpage - % ============================================== % % ===========================(start ex 07) % -\chapter{Exercise 07} -\extitle{Komparator} -\turnindir{ex07} -\exnumber{07} -\exfiles{Komparator.py, MyPlotLib.py (optional)} -\exforbidden{None} -\makeheaderfilesforbidden - - -% ================================= % -\section*{Objective} -% --------------------------------- % -The goal of this exercise is to introduce plotting methods among the different -libraries Pandas, Matplotlib, Seaborn or Scipy. - -% ================================= % -\section*{Instructions} -% --------------------------------- % -This exercise uses the following dataset: \texttt{athlete\_events.csv}. - - -Write a class called \texttt{Komparator} whose constructor takes as an argument a pandas.DataFrame which contains the dataset. - -The class must implement the following methods, which take as input two variable names: -\begin{itemize} - \item \texttt{compare\_box\_plots(self, categorical\_var, numerical\_var)}: displays a series of box plots - to compare how the distribution of the numerical variable changes if we only consider - the subpopulation which belongs to each category. - There should be as many box plots as categories. - For example, with Sex and Height, we would compare - the height distributions of men vs. women with two box plots. - \item \texttt{density(self, categorical\_var, numerical\_var)}: displays the density of the numerical variable. - Each subpopulation should be represented by a separate curve on the graph. - \item \texttt{compare\_histograms(self, categorical\_var, numerical\_var)}: plots the numerical variable in a separate histogram for each category. - As an extra, you can use overlapping histograms with a color code. -\end{itemize} - -BONUS: Your functions can also accept a list of numerical variables (instead of just one), and output a comparison plot for each variable in the list. - +\input{exercises/m04ex07.tex} % ===========================(fin ex 07) % % ============================================== % - \newpage - -% ================================= % -\section*{Contact} -% --------------------------------- % -You can contact 42AI association by email: contact@42ai.fr\\ - -If you are a student from 42, you can access our Discord server -on \href{https://discord.com/channels/887850395697807362/887850396314398720}{42 student's associations portal} and ask your -questions to your peers in the dedicated Bootcamp channel. - -Find all the relevant and up-to-date information about 42AI on \href{https://42-ai.github.io}{our Website} ! - -Thank you for attending this Python Bootcamp module04 ! -% ================================= % -\section*{Acknowledgements} -% --------------------------------- % -The modules Python \& ML is the result of a collective work, we would like to thank: -\begin{itemize} - \item Maxime Choulika (cmaxime), - \item Pierre Peigné (ppeigne, pierre@42ai.fr), - \item Matthieu David (mdavid, matthieu@42ai.fr), - \item Quentin Feuillade--Montixi (qfeuilla, quentin@42ai.fr) -\end{itemize} -who supervised the creation, the enhancement and this present transcription. - -\begin{itemize} - \item Louis Develle (ldevelle, louis@42ai.fr) - \item Augustin Lopez (aulopez) - \item Luc Lenotre (llenotre) - \item Owen Roberts (oroberts) - \item Thomas Flahault (thflahau) - \item Amric Trudel (amric@42ai.fr) - \item Baptiste Lefeuvre (blefeuvr@student.42.fr) - \item Mathilde Boivin (mboivin@student.42.fr) - \item Tristan Duquesne (tduquesn@student.42.fr)- Mathieu Perez (mathieu.perez@42ai.fr) -\end{itemize} -for your investment for the creation and development of these modules. - -\begin{itemize} - \item Barthélémy Leveque (bleveque@student.42.fr) - \item Remy Oster (roster@student.42.fr) - \item Quentin Bragard (qbragard@student.42.fr) - \item Marie Dufourq (madufour@student.42.fr) - \item Adrien Vardon (advardon@student.42.fr) -\end{itemize} -who betatest the first version of the modules of Machine Learning. -\vfill -\doclicenseThis - +\input{en.acknowledgements.tex} \end{document} \ No newline at end of file diff --git a/resources/latex/Makefile.LaTeX b/resources/latex/Makefile.LaTeX index 05d94b0c..e80bfe9d 100644 --- a/resources/latex/Makefile.LaTeX +++ b/resources/latex/Makefile.LaTeX @@ -26,7 +26,7 @@ export TEXINPUTS := ..:.:$(RELPATH):${TEXINPUTS}: all: $(TARGETS) clean: - rm -f *.aux *.ent *.log *.out *.toc *.nav *.snm *.vrb *.pyg + rm -f *.aux *.ent *.log *.out *.toc *.nav *.snm *.vrb *.pyg *.pdf.version *.fls *.fdb_latexmk distclean: clean rm -f $(TARGETS) diff --git a/version b/version index 51033692..0fa4ae48 100644 --- a/version +++ b/version @@ -1 +1 @@ -v3.2.3 +3.3.0 \ No newline at end of file