From cc8ee1615b0871057446fe0d4386409a4e71dc9a Mon Sep 17 00:00:00 2001 From: Davide Grilli Date: Wed, 29 Apr 2026 13:32:32 +0200 Subject: [PATCH] Aggiunge esercizio 45 --- lab45.py | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ lab45.txt | 5 +++++ 2 files changed, 69 insertions(+) create mode 100644 lab45.py create mode 100644 lab45.txt diff --git a/lab45.py b/lab45.py new file mode 100644 index 0000000..bd9c4d8 --- /dev/null +++ b/lab45.py @@ -0,0 +1,64 @@ +from os import strerror + + +class StudentsDataException(Exception): + pass + + +class BadLine(StudentsDataException): + def __init__(self, line_number, line): + message = "Riga " + str(line_number) + ": " + line.rstrip() + super().__init__(message) + + +class FileEmpty(StudentsDataException): + def __init__(self): + super().__init__("il file esiste, ma e' vuoto") + + +file_name = input("Inserisci il nome del file del Prof. Jekyll: ") +students = {} + +try: + stream = open(file_name, "rt", encoding="utf-8") + lines = stream.readlines() + stream.close() + + if len(lines) == 0: + raise FileEmpty() + + for line_number, line in enumerate(lines, 1): + parts = line.split() + + # Ogni riga deve avere esattamente: nome, cognome, punti. + if len(parts) != 3: + raise BadLine(line_number, line) + + first_name = parts[0] + last_name = parts[1] + + try: + # Accettiamo sia il punto sia la virgola come separatore decimale. + points = float(parts[2].replace(",", ".")) + except ValueError: + raise BadLine(line_number, line) + + student = first_name + " " + last_name + + if student in students: + students[student] += points + else: + students[student] = points + + if len(students) == 0: + raise FileEmpty() + + for student in sorted(students.keys()): + print(student, students[student]) + +except FileEmpty as e: + print("Errore:", e) +except BadLine as e: + print("Errore nei dati di input:", e) +except IOError as e: + print("Errore di I/O:", strerror(e.errno)) diff --git a/lab45.txt b/lab45.txt new file mode 100644 index 0000000..2d26cc9 --- /dev/null +++ b/lab45.txt @@ -0,0 +1,5 @@ +John Smith 5 +Anna Bolena 4,5 +John Smith 2 +Anna Bolena 11 +Andrew Cox 1,5