Commit 4166e29a authored by Raffaele Grosso's avatar Raffaele Grosso
Browse files

Add exercises for Python classes.

parent 5c1bfd3c
......@@ -7,7 +7,7 @@
\usepackage[T1]{fontenc}
\usepackage{relsize}
\newcommand{\Hint}[1]{{\color{Blue} Hint:} #1}
\usepackage{listings}
\usepackage{fancyhdr}
\pagestyle{fancy}
......@@ -15,31 +15,41 @@
\rhead{\thepage}
\lhead{Python Exercises for Trainees}
\newcommand{\Hint}[1]{{\\ \color{Blue} Hint:} #1}
\newcommand{\HintN}[2]{{\\ \color{Blue} Hint #1:} #2}
\newcommand{\Example}[1]{{\\ \color{Blue} Example:} #1}
\newcounter{ChapterCounter}
\newcommand{\Chapter}[1]{\refstepcounter{ChapterCounter}\textbf{\theChapterCounter. #1 \label{#1}}}
\begin{document}
\Chapter{Hello World and basic I/O}
\lstset{language=Python}
\Chapter{Hello World, basic I/O and importing a module}
\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 might be necessary.}
\HintN{2}{To get the current year and avoid to hardcode it you should use the appropriate function from the \texttt{datetime} module, therefore \texttt{import} it.}
\end{enumerate}
\Chapter{Lists}
\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.
\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 a list object.}
\\ {\color{Blue} Example:} ``\textit{I like this color}'' should give ``\textit{color this like I}''
\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{``\textit{I like this color}'' should give ``\textit{color this like I}''.}
\item \label{1} Write a program which returns in alphabetical order the words of a sentence received as input.
\\ {\color{Blue} Example:} the example above should give ``\textit{I color like this}''
\Example{The previous example should give ``\textit{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 ``\textit{color I like this}''.}
\end{enumerate}
\Chapter{Dictionaries}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a program filling a dictionary with ten name-birthday pairs requested as input and printing out the month of birth for the names chosen by the user.
\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}
......@@ -47,28 +57,76 @@
\item Write a ``guess the number'' game: the user guesses an integer between 1 and 10 until he/she enters "exit" or until she 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 a file and writing it to a second file after replacing newlines with spaces. The two file names are to be given as input.
\item Now the program should fill a dictionary with key-value pairs read from a first json file and write them to a second json file after having added or replaced a few entries according to input given by the user.
\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.
\end{enumerate}
\Chapter{Functions}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Write a program which, by means of a function, prints out a sketched chessboard: the first, last and all odd lines are a sequence of dashes while the even lines are a sequence of spaced vertical bars.
\item Write a program which, by means of a function, prints out a sketched chessboard: the first, last and all odd lines are a sequence of dashes while the even lines are a sequence of spaced vertical bars, like in the sketch below.\\
\begin{verbatim} ----------------------------------------
| | | | | | | | | | |
----------------------------------------
| | | | | | | | | | |
----------------------------------------
\end{verbatim}
\end{enumerate}
Lambda functions:
\begin{enumerate}[label=\textbf{\alph*)}]
\item Like in exercise \ref{Lists}.\ref{1} but with case insensitive order. \Hint{You can pass a lambda function as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted} e ``\texttt{key=}''}
\item Like in exercise \ref{Lists}.\ref{2} but this time you are supposed to pass a lambda function as ``\texttt{key=}'' argument of \texttt{sort} or \texttt{sorted}, using the \texttt{lower} function of a string object.
\\ {\color{Blue} Example:} ``\textit{I like this color}'' should give ``\textit{color I like this}''
\end{enumerate}
\Chapter{Exception handling}
Write a program that reads a number from a file and then devides 100 by this number.
\begin{enumerate}[label=\textbf{\alph*)}]
\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
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.
\end{enumerate}
\Chapter{Classes and Objects}
\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:
\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
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
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.
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:
\texttt{x.\_\_len\_\_()} for \texttt{len(x)} \\
\texttt{x.\_\_getitem\_\_(i)} for \texttt{x[i]} \\
\texttt{x.\_\_setitem\_\_(i, y)} for \texttt{x[i] = y} \\
\texttt{x.\_\_delitem\_\_(i)} for \texttt{del x[i]} \\
\texttt{x.\_\_contains\_\_(y)} for \texttt{y in x}.
\end{enumerate}
\Chapter{Plots and Histograms}
\begin{enumerate}[label=\textbf{\alph*)}]
\item Plot an histogramm with the distribution of births per month from Exercise \ref{Dictionaries}.
\item Plot an histogramm with the distribution of births per month from exercise \ref{Dictionaries}.\ref{3}.
\end{enumerate}
\end{document}
#!/usr/bin/python3
from argparse import ArgumentParser
import json
# read arguments
parser = ArgumentParser()
parser.add_argument('filename', help='The name of the file containing the dictionary.')
args = parser.parse_args()
try:
with open(args.filename, "r") as infile:
Wort = json.load(infile)
print("The currently stored dictionary looks like:")
print(Wort)
except FileNotFoundError as fnf:
print(fnf)
quit()
except json.decoder.JSONDecodeError:
print("The content of the file cannot be decoded into a dictionary (possible syntax error)")
quit()
# If the user wants to modify the dictionary stored in the file:
while True:
modify = input("Do you want to modify or add key-value pairs? (Yn)")
if modify.lower() == "y" or not modify:
while True:
key = input("Please enter a key (you can quit by typing 'quit'): ")
if key == "quit":
break
value = input("Please enter a value (you can quit by typing 'quit'): ")
if value == "quit":
break
Wort[key] = value
with open(args.filename, "w") as outfile:
json.dump(Wort, outfile)
print("The newly stored dictionary looks like:")
print(Wort)
break
elif modify.lower() == "n":
break
else:
print("Not a valid choice. Please enter 'y' or 'n'")
Supports Markdown
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