Commit 942f781d authored by Raffaele Grosso's avatar Raffaele Grosso
Browse files

Add Python exercises.

parent 9e112356
\documentclass[10pt,a4paper]{letter}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
%\usepackage{amsmath}
\usepackage{stix}
\usepackage{enumitem}
\usepackage{bm}
\usepackage[margin=4.2cm]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
......@@ -26,9 +26,21 @@
\newcommand{\ChapterNoNum}[1]{\begin{center}\textbf{#1}\end{center} \label{#1}}
\renewcommand\labelitemi{-}
% for item labels prefixed with an asterisk
\newcommand{\sitem}[1][black]{\stepcounter{enumi}\item[\color{#1}$\bm{*}$\,\textbf{\theenumi}]}
\begin{document}
\lstset{language=Python}
\lstset{language=Python, basicstyle=\small\ttfamily, showstringspaces=false}
\noindent\fbox{%
\parbox{\textwidth}{%
\begin{itemize}
\item[$\rightarrow$] Hints and notes refer to Python 3.
\item[$\rightarrow$] Difficult exercises are marked with an asterisk, indicating that they can be at first omitted or simply skipped if overchallenging.
\end{itemize}
}%
}
\ChapterNoNum{Preliminaries}
Composing, formatting, printing strings. Reading values from the prompt into a variable. Importing a module. Checking the type of a variable.
......@@ -48,17 +60,18 @@ Composing, formatting, printing strings. Reading values from the prompt into a v
\Chapter{Reading values from the prompt - Formatting strings}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a Hello World program, that is a program that just writes: \texttt{"Hello World!"}
\item Write a program which asks the user its name and birth year and then writes the following text: \texttt{"Hi NAME, you will become X years old this year."}.
\HintN{1}{The \texttt{input} and \texttt{raw\_input} functions take as argument a string to be prompted to the user and return the user's input. These two functions differ between Python version 2 or 3. Mind the type of the returned object, casting it in case.}
\item Write a Hello World program, that is a program that just writes: \lstinline{"Hello World!"}
\item Write a program which asks the user its name and birth year and then writes the following text: \lstinline{"Hi NAME, you will become X years old this year."}.
\HintN{1}{In Python 3 the \texttt{input} function takes as argument a string to be prompted to the user and return the user's input string. Cast it if appropriate.}
\HintN{2}{To get the current year and avoid to hardcode it, you should use the appropriate function from the \texttt{datetime} module and therefore \texttt{import} it.}
\HintN{3}{To format variables into a string there are various methods. You can try and then choose one of the following:
\begin{itemize}
\item \texttt{f"my text contains the value of \{var1\} and of \{var2\}"}
\item \texttt{"my text contains the value of \{0:\} and of \{1:\}".format(var1, var2)}
\item \texttt{"my text contains the value of \%s and of \%d" \% (var1, var2)}
\end{itemize}
}
%\HintN{3}{To format variables into a string there are various methods. You can try and then choose one of the following:
\\{\color{Blue} Hint 3:} To format variables into a string there are various methods. You can try and then choose one of the following:
\begin{lstlisting}[language=Python]
f"var1: {var1} var2: {var2}"
"var1: {0:8s} var2: {1:4.2f}".format(var1, var2)
"var1: %s var2: %d" % (var1, var2)
\end{lstlisting}
%}
\end{enumerate}
......@@ -78,17 +91,17 @@ Make sure you know the main characteristics of \texttt{list}s, \texttt{tuple}s,
\item sort and revert the order of elements in the list
\end{itemize}
\item Which methods of the list above would help you using a list as a \textit{stack} (or \textit{LIFO}: Last In First Out)?
\item Lists are not good to be used as a \textit{queue} (or \textit{FIFO}: First In First Out). Why?
\sitem Lists are not good to be used as a \textit{queue} (or \textit{FIFO}: First In First Out). Why?
\Note{For that purpose you can use \texttt{collections.deque}, which provides a \texttt{popleft} method.}
%\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a program that fills a list with ten integers taken as input from the terminal and returns only the even ones.
\sitem Write a program that fills a list with ten integers taken as input from the terminal and returns only the even ones.
\Hint{Use a \textit{list comprehension}.}
\item Write a program which returns in reversed order the words of a sentence received as input.
\Hint{Use the ``\textit{extended slice syntax}'' \texttt{[::-1]}. Alternatively use the \texttt{reverse} function of list objects.}
\Example{``\texttt{I like this color}'' should give ``\texttt{color this like I}''.}
\item \label{1} Write a program which returns in alphabetical order the words of a sentence received as input.
\Example{The previous example should give ``\texttt{I color like this}''.}
\item \label{2} Like in the previous exercise (\ref{Lists}.\ref{1}) but case insensitive. \Hint{You can pass the \texttt{str.lower} function as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted}.}
\Example{The previous example should give ``\lstinline{I color like this}''.}
\sitem \label{2} Like in the previous exercise (\ref{Lists}.\ref{1}) but case insensitive. \Hint{You can pass the \texttt{str.lower} function as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted}.}
\Example{The previous example should give ``\texttt{color I like this}''.}
\end{enumerate}
......@@ -105,22 +118,31 @@ Make sure you know the main characteristics of \texttt{list}s, \texttt{tuple}s,
\item \label{3} Write a program that fills a dictionary with ten (name - birthday month) key-value pairs requested as input and prints out the month of birth for the names chosen by the user.
\end{enumerate}
\Chapter{Conditions and loops}
\vspace{0.5cm}
\ChapterNoNum{Control flow}
Keywords like \texttt{if}, \texttt{else}, \texttt{while}, \texttt{for}, \texttt{pass}, \texttt{break}, \ldots allow to shape the flow of statements to be executed.
\Chapter{Conditions and Loops}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Make sure you can correctly use \texttt{if-else}-statements and \texttt{for}- and \texttt{while}-loops, in particular the construct ``\texttt{for i in}'' plus \texttt{range()} or plus an iterable.
\item Make sure you can correctly use \texttt{if-elif-else}-statements
\item Make sure you can correctly use \texttt{for}- and \texttt{while}-loops, in particular the construct ``\texttt{for i in}'' plus \texttt{range()} or plus an iterable.
\item List the arguments passed to your script.
\Hint{Using the \texttt{sys} module, \texttt{sys.argv} is a list containing the arguments.}
\item Write a ``guess the number'' game: the user guesses an integer between 1 and 10 until (s)he enters \texttt{exit} or until (s)he gets the right number.
\end{enumerate}
\vspace{2cm}
\Chapter{File I/O}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a program reading a text from an input file and writing it to an output file after replacing newlines with spaces. The two file names are to be given as input.
\item Write a program that fills a dictionary with key-value pairs read from a first json file and writes out the dictionary to a second json file after having added or replaced a few entries according to input given by the user.
\sitem Write a program that fills a dictionary with key-value pairs read from a first json file and writes out the dictionary to a second json file after having added or replaced a few entries according to input given by the user.
\Hint{Use the \texttt{dump} and \texttt{laod} functions provided by the \texttt{json} module.}
\end{enumerate}
\vspace{0.5cm}
\ChapterNoNum{Functions and Modules}
The exercises in this unit ask you to define functions -- blocks of callable code -- and to write and import modules -- files containing Python code which can be imported and utilised by other Python code.
\Chapter{Functions}
\begin{enumerate}[label=\textbf{\alph*)}]
\item
......@@ -138,10 +160,27 @@ $\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblks
$\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare$\\
$\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare\lgblksquare\lgwhtsquare$
\end{minipage}
\item Write a docstring for both of this functions and verify it gets called when it should (in an interactive Python shell) or call it explicitly with \texttt{.\_\_doc\_\_}
\item Like in exercise \ref{Lists}.\ref{2} but this time you are supposed to pass a \textit{lambda function} as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted}, using the \texttt{lower} function of a string object.
\sitem Write a docstring for both of this functions and verify it gets called when it should (in an interactive Python shell) or call it explicitly with \texttt{.\_\_doc\_\_}
\sitem Like in exercise \ref{Lists}.\ref{2} but this time you are supposed to pass a \textit{lambda function} as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted}, using the \texttt{lower} function of a string object.
\Example{``\texttt{I like this color}'' should give ``\texttt{color I like this}''}
\item Make a minimal example showing the effect of defining a variable inside a function with or without the keyword \texttt{global}.
\sitem Make a minimal example showing the effect of defining a variable inside a function with or without the keyword \texttt{global}.
\end{enumerate}
\Chapter{Modules}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Create a module (a file named \texttt{a\_sort.py}) containing the two functions \texttt{sort\_alpha} and \texttt{i\_sort\_alpha} taking as argument a string and returning the corresponding list of component words sorted alfabetically (case insensitive in the case of the second function).
\item From a script or an interactive shell import the module in the following ways:
\begin{enumerate}[label=\textbf{\roman*)}]
\item \texttt{import a\_sort}
\item \texttt{import a\_sort as srt}
\item \texttt{from a\_sort import *}
\end{enumerate}
and make use of the two functions.
\sitem Complete the module with a \texttt{if \_\_name\_\_ == "\_\_main\_\_":} block so that the functions are executed when executing the module but not when loading it.
\item Use the \texttt{dir} function to inspect the name space of the imported module.
\sitem Write and use a package, that is a tree of modules inside a common directory where a \texttt{\_\_init\_\_.py} is provided.
\Note{The \lstinline{__init__.py} file is supposed to define which modules are to be exported (the so called \textit{API} of the package) and which not (the internal modules).}
\end{enumerate}
......@@ -152,32 +191,35 @@ Write a program that reads a number from a file and then devides 100 by this num
\item Try opening a non-existent file. Make sure you understand what happens.
\item Same as above, but this time you don't want the program to terminate but to
print an error message.
\item In addition to the previous point, your program should not terminate but print out a different error statement
\sitem In addition to the previous point, your program should not terminate but print out a different error statement
for the different possible error cases (generate them by varying the content of the file).
\item Add an action to be executed in case an error occured, which were not catched by previous \texttt{except} statements.
\item Add an action to be executed at any execution of the try statement.
\sitem Add an action to be executed in case an error occured, which were not catched by previous \texttt{except} statements.
\sitem Add an action to be executed at any execution of the try statement.
\end{enumerate}
\vspace{0.5cm}
\ChapterNoNum{Object Oriented Programming}
\Chapter{Classes and Objects}
\Chapter{Classes}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a class to implement a Fibonacci iterator: assuming your class is called \texttt{fib\_iter}, this is its expected behaviour:
\sitem Write a class to implement a Fibonacci iterator: assuming your class is called \texttt{fib\_iter}, this is its expected behaviour:
\begin{lstlisting}
for i in fib_iter(500):
print(i, end=' ')
\end{lstlisting}
will return: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
{\color{Blue}Theory: }To conform to the paradigm of the Python iterator, the class needs
\\{\color{Blue}Theory: }To conform to the paradigm of the Python iterator, the class needs
to implement an \texttt{\_\_iter\_\_} method (usully returning \texttt{self}) and a
\texttt{\_\_next\_\_} method, which defines what is returned at each iteration and when
the loop should be exited by raising a \texttt{StopIteration} exception. The
\texttt{for} loop creates an iterator by calling behind the scenes the \texttt{\_\_iter\_\_} method
and then calles the \texttt{\_\_next\_\_} method at each iteration.
\item Instantiate an object of \texttt{fib\_iter} and display the value of its members after
\sitem Instantiate an object of \texttt{fib\_iter} and display the value of its members after
manually calling \texttt{object.\_\_next\_\_()}.
\item Add a docstring to the class and have it desplayed (use \texttt{fib\_iter.\_\_doc\_\_}).
\item Similiarly, you can create your own collection class by following the collection protocol.
\sitem Add a \textit{docstring} to the class and have it desplayed (use \texttt{fib\_iter.\_\_doc\_\_}).
\sitem Similiarly, you can create your own collection class by following the collection protocol.
Create a class representing a collection of files in a directory in form of a dictionary, where keys are the filenames of the files contained in the directory and values are the corresponding contents.\\
%http://zesty.ca/bc/explore-11.html
{\color{Blue}Theory: }To conform to the collection protocol define the following methods:
......@@ -189,10 +231,21 @@ Write a program that reads a number from a file and then devides 100 by this num
\end{enumerate}
\vspace{0.5cm}
\ChapterNoNum{Libraries}
Python provides a very rich standard library and a huge set of other libraries for specific uses. These are usually available as packages which you might need to explicitly install on your system.
For the exercises below, for example, you are supposed to use the \texttt{matplotlib} library for plotting and producing figures and the \texttt{numpy} library for generating functions and dealing with arrays.
\Chapter{Plots and Histograms}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Plot an histogramm with the distribution of births per month from exercise \ref{Dictionaries}.\ref{3}.
\sitem Plot the function $f(x) = 1 + sin(3x)$ in the range $[0,4]$ labelling the axis and adding a grid.
\Hint{Use the \texttt{pyplot.subplots} function from the module \texttt{matplotlib} and \texttt{sin} from \texttt{numpy}.}
%https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html#sphx-glr-gallery-lines-bars-and-markers-simple-plot-py
\item Plot an histogram with the distribution of births per month from exercise \ref{Dictionaries}.\ref{3}.
\Hint{Use the \texttt{pyplot.hist} function from the module \texttt{matplotlib}.}
%https://matplotlib.org/gallery/statistics/histogram_features.html
\sitem Histogram a randomly generated distribution around a gaussian and add a best fit line.
\Hint{Use the \texttt{np.random.randn} to generate the distribution.}
\end{enumerate}
\end{document}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment