Skip to content

Commit fa309e8

Browse files
committed
Esercitazione 7
1 parent a9b0831 commit fa309e8

File tree

9 files changed

+102917
-0
lines changed

9 files changed

+102917
-0
lines changed

data/u.item

Lines changed: 1682 additions & 0 deletions
Large diffs are not rendered by default.

data/u.user

Lines changed: 943 additions & 0 deletions
Large diffs are not rendered by default.

data/u1.base

Lines changed: 80000 additions & 0 deletions
Large diffs are not rendered by default.

data/u1.test

Lines changed: 20000 additions & 0 deletions
Large diffs are not rendered by default.

latex/esercitazioni/es_7.pdf

123 KB
Binary file not shown.

latex/esercitazioni/es_7.tex

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
\documentclass[11pt,a4]{article}
2+
3+
\usepackage[margin=2cm]{geometry}
4+
5+
\usepackage{amsmath}
6+
\usepackage{url}
7+
8+
\usepackage{amsmath}
9+
\usepackage{url}
10+
11+
\usepackage[utf8]{inputenc}
12+
13+
% Default fixed font does not support bold face
14+
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{10} % for bold
15+
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{10} % for normal
16+
17+
% Custom colors
18+
\usepackage{color}
19+
\definecolor{deepblue}{rgb}{0,0,0.5}
20+
\definecolor{deepred}{rgb}{0.6,0,0}
21+
\definecolor{deepgreen}{rgb}{0,0.5,0}
22+
23+
\usepackage{listings}
24+
25+
% Python style for highlighting
26+
\newcommand\pythonstyle{\lstset{
27+
language=Python,
28+
basicstyle=\ttm,
29+
otherkeywords={self}, % Add keywords here
30+
keywordstyle=\ttb\color{deepblue},
31+
emph={MyClass,__init__}, % Custom highlighting
32+
emphstyle=\ttb\color{deepred}, % Custom highlighting style
33+
stringstyle=\color{deepgreen},
34+
frame=tb, % Any extra options here
35+
showstringspaces=false %
36+
}}
37+
38+
39+
% Python environment
40+
\lstnewenvironment{python}[1][]
41+
{
42+
\pythonstyle
43+
\lstset{#1}
44+
}
45+
{}
46+
47+
% Python for external files
48+
\newcommand\pythonexternal[2][]{{
49+
\pythonstyle
50+
\lstinputlisting[#1]{#2}}}
51+
52+
% Python for inline
53+
\newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}
54+
55+
56+
\usepackage{collectbox}
57+
58+
\newcommand{\mybox}[2]{$\quad$\fbox{
59+
\begin{minipage}{#1cm}
60+
\hfill\vspace{#2cm}
61+
\end{minipage}
62+
}}
63+
64+
65+
\usepackage{fancyhdr}
66+
\pagestyle{fancy}
67+
\rhead{Programmazione 1 - Esercitazione 7}
68+
69+
\include{book_header}
70+
71+
\begin{document}
72+
\thispagestyle{empty}
73+
\hrule
74+
\begin{center}
75+
{\Large {\bf Programmazione 1 \hspace{3cm} $\quad \quad \quad$ Esercitazione 7}}
76+
\end{center}
77+
{\bf Cognome: }\hspace{2.5cm} {\bf Nome: } \hspace{2.5cm} {\bf Matricola: } \\\
78+
\hrule
79+
80+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
81+
\section*{}
82+
Questa è la prima di due esercitazioni che vi guideranno alla scrittura di un programma che possa fare delle semplici previsioni
83+
sui voti che un utente potrebbe dare a dei film che non ha ancora valutato.
84+
85+
L'obiettivo didattico dell'esercitazione è di far pratica nello scrivere programmi per la lettura di file di testo,
86+
nella costruzione di liste di liste o tuple, e nell'uso di dizionari. Si consiglia pertanto di ripassare
87+
il contenuto del notebook Lab 10.
88+
89+
Per questa esercitazione si devono usare i seguenti file di testo (i dati sono reali):
90+
\begin{enumerate}
91+
\item {\tt u.user}: contiene le informazioni sugli utenti.
92+
\item {\tt u.item}: contiene le informazioni sui film.
93+
\item {\tt u1.base}: contiene le valutazioni degli utenti ai film, su una scala da 1 a 5.
94+
\end{enumerate}
95+
96+
L'esercitazione va svolta andando completare il codice per le funzioni contenute nel file {\tt Testing\_es\_7.py} disponibile sul sito. Gli esercizi da svolgere in ordine sono:
97+
98+
\begin{enumerate}
99+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
100+
\item Scrivere una funzione {\tt ParseUsers(filename)} che legge il file di testo chiamato {\tt filename}
101+
e restituisce una lista di tuple, in cui ogni tupla contiene le informazioni di un utente.
102+
Il file di input contiene una riga per ogni utente con le informazioni seguenti:
103+
\begin{center}
104+
{\tt user id | age | gender | occupation | zip code}
105+
\end{center}
106+
107+
\mybox{15}{2}
108+
109+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
110+
\item Scrivere una funzione {\tt CountGender(Ls)} che prende in input la lista di tuple {\tt Ls}
111+
contenente le informazioni degli utenti e conta il numero di utenti per ogni {\it gender}.
112+
113+
Il risultato dovrebbe essere 273 utenti di sesso femminile e 670 di sesso maschile.
114+
115+
\mybox{15}{2}
116+
117+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
118+
\item Scrivere una funzione {\tt CountOccupation(Ls)} che prende in input la lista di tuple {\tt Ls}
119+
contenente le informazioni degli utenti e conta il numero di utenti per ogni tipo di occupazione.
120+
Il conteggio viene memorizzato in un dizionario in cui la chiave è il tipo di occupazione, mentre il valore
121+
è il rispettivo numero di utenti.
122+
123+
\mybox{15}{2.5}
124+
125+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
126+
\item Scrivere una funzione {\tt CountAge(Ls)} che prende in input la lista di tuple {\tt Ls}
127+
contenente le informazioni degli utenti e conta il numero di utenti per le seguenti fasce di età:
128+
$(x<18, 18\leq x <25, 25 \leq x < 40, 40 \leq x < 65, x > 65)$. La funzione deve restituire una lista
129+
con i valori per le relative fasce di età.
130+
131+
\mybox{15}{2.5}
132+
133+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
134+
\item Scrivere una funzione {\tt ParseFilm(filename)} che legge il file {\tt filename}
135+
e restituisce un dizionario, in cui ogni chiave è l'id di un film e il rispettivo valore
136+
è lista con le informazioni sul film.
137+
Il file di input contiene una riga per ogni film, e ogni riga contiene in ordine le informazioni seguenti:
138+
\begin{center}
139+
{\tt movie id|movie title|release date|video release date|IMDb URL|unknown|Action|
140+
Adventure|Animation|Children's|Comedy|Crime|Documentary|Drama|Fantasy|Film-Noir|
141+
Horror|Musical|Mystery|Romance|Sci-Fi|Thriller|War|Western}
142+
\end{center}
143+
144+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
145+
\item Scrivere una funzione {\tt CountItem(Fs, i):} che prende in input un dizionario {\tt Fs} come
146+
restituito dalla funzione precedente, e un indice {\tt i}>5, e conta il numero di film con il genere
147+
corrispondente all'$i$-esimo elemento della lista che descrive un film. Per esempio,
148+
il numero di film thriller è 251.
149+
150+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
151+
\item Scrivere una funzione {\tt CountYears(Fs):} che prende in input un dizionario {\tt Fs} come
152+
restituito dalla funzione precedente, e conta il numero di film usciti in ogni anno. Per contare l'anno,
153+
si deve elaborare il campo {\tt release date} estraendone l'anno (si consiglia di usare la funzione {\tt split}).
154+
Per esempio, si dovrebbe ottenere che nel 1996 sono usciti 355 film.
155+
156+
\mybox{15}{2}
157+
158+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
159+
\item Scrivere una funzione {\tt ParseRating(filename)} che legge il file {\tt filename}
160+
e restituisce una lista di liste, una per ogni rating.
161+
Il file di input contiene le informazioni seguenti:
162+
\begin{center}
163+
{\tt user id | item id | rating | timestamp}
164+
\end{center}
165+
166+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
167+
\item Scrivere una funzione {\tt CountFiled(Ls, i)} che prende in input una lista di rating
168+
e un indice i < 3, e per ogni elemento della lista conta il numero di occorrenze diverse.
169+
Questa funzione può essere usata per contare il numero di volte che ciascun voto è stato dato
170+
(usata con $i=2$), il numero di voti dati da ciascun utente ($i=0$), oppure il numero
171+
di voti ricevuti da ciascun film ($i=1$).
172+
173+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
174+
\item Scrivere una funzione {\tt PrintTopFilm(Ds, top, Ts)} che prende in input un
175+
dizionario che ha una chiave per ogni film con il valore del numero di voti ricevuti,
176+
un numero intero {\tt top}, e il dizionario che mappa ogni id di un film nelle sua lista di informazioni,
177+
e stampi a video il titolo e il numero di valutazioni per i primi {\tt top} film più votati.
178+
179+
\mybox{15}{2}
180+
181+
\end{enumerate}
182+
183+
\end{document}

latex/soluzioni/sol_es_2.pdf

8.93 KB
Binary file not shown.

latex/soluzioni/sol_es_2.tex

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
% Python style for highlighting
2323
\newcommand\pythonstyle{\lstset{
2424
language=Python,
25+
numbers=left,
26+
numberstyle=\tiny\color{black},
2527
basicstyle=\ttm,
2628
otherkeywords={self}, % Add keywords here
2729
keywordstyle=\ttb\color{deepblue},

scripts/Testing_es_7.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Wed Dec 6 10:47:43 2017
4+
5+
@author: gualandi
6+
"""
7+
8+
# -*- coding: utf-8 -*-
9+
"""
10+
Created on Tue Dec 5 21:45:33 2017
11+
12+
@author: gualandi
13+
"""
14+
15+
# Parse a file where for each row we have:
16+
# user id | age | gender | occupation | zip code
17+
# 1|24|M|technician|85711
18+
def ParseUsers(filename):
19+
fh = open(filename, 'r', encoding="utf-8")
20+
Rs = []
21+
# DA COMPLETARE
22+
return Rs
23+
24+
def CountGender(Ls):
25+
D = {}
26+
# DA COMPLETARE
27+
return D
28+
29+
def CountOccupation(Ls):
30+
D = {}
31+
# DA COMPLETARE
32+
return D
33+
34+
def CountAge(Ls):
35+
R = [0,0,0,0,0]
36+
# DA COMPLETARE
37+
return R
38+
39+
# Info for each film:
40+
# movie id | movie title | release date | video release date |
41+
# IMDb URL | unknown | Action | Adventure | Animation |
42+
# Children's | Comedy | Crime | Documentary | Drama | Fantasy |
43+
# Film-Noir | Horror | Musical | Mystery | Romance | Sci-Fi |
44+
# Thriller | War | Western |
45+
def ParseFilm(filename):
46+
fh = open(filename, 'r')
47+
Rs = {}
48+
# DA COMPLETARE
49+
return Rs
50+
51+
def CountItem(Fs, i):
52+
t = 0
53+
# DA COMPLETARE
54+
return t
55+
56+
def CountYears(Fs):
57+
D = {}
58+
# DA COMPLETARE
59+
return D
60+
61+
# user id | item id | rating | timestamp
62+
def ParseRatings(filename):
63+
fh = open(filename, 'r')
64+
Rs = []
65+
# DA COMPLETARE
66+
return Rs
67+
68+
def CountField(Ls, v):
69+
D = {}
70+
# DA COMPLETARE
71+
return D
72+
73+
def PrintTop(Ds, top=5):
74+
for key in sorted(Ds, key=Ds.get, reverse=True)[:top]:
75+
print(key, Ds[key])
76+
77+
def PrintTopFilm(Ds, top, Ts):
78+
# DA COMPLETARE
79+
pass
80+
81+
#-----------------------------------------------
82+
# MAIN function: da usare in fase di test
83+
#-----------------------------------------------
84+
if __name__ == "__main__":
85+
Ls = ParseUsers('../data/u.user')
86+
87+
print(CountGender(Ls))
88+
Os = CountOccupation(Ls)
89+
PrintTop(Os)
90+
print(CountAge(Ls))
91+
92+
Ls = ParseFilm('../data/u.item')
93+
PrintTop(Ls)
94+
print(CountItem(Ls, 20)) # 251
95+
Fs = CountYears(Ls)
96+
PrintTop(Fs)
97+
98+
99+
Rs = ParseRatings('../data/u1.base')
100+
print()
101+
PrintTop(CountField(Rs, 2))
102+
print()
103+
PrintTop(CountField(Rs, 0))
104+
print()
105+
PrintTop(CountField(Rs, 1))
106+
print()
107+
PrintTopFilm(CountField(Rs, 1), 10, Ls)

0 commit comments

Comments
 (0)