Compare commits

...
34 Commits
Author SHA1 Message Date
davide fe4883cde8 aggiunge esercizio 48 2026-05-04 18:49:57 +02:00
davide c048527f38 aggiunge esercizio 47 2026-05-04 18:08:56 +02:00
davide 2aeaadfe18 Aggiunge esercizio 46 2026-04-30 15:48:08 +02:00
davide cc8ee1615b Aggiunge esercizio 45 2026-04-29 13:32:32 +02:00
davide 07d1e9dd75 aggiunge esercizio 44 2026-04-29 12:29:58 +02:00
davide 722e008efa aggiunge esercizio 43 2026-04-29 12:25:28 +02:00
davide ed29b5907c aggiunge esercizio 42 2026-04-13 15:59:41 +02:00
davide e420bae5d5 aggiunge esercizio 41 2026-04-13 15:56:49 +02:00
davide 1200160f1c aggiunge esercizio 40 2026-04-13 15:47:19 +02:00
davide ca2901f4e3 aggiunge dispense (2 parte) 2026-04-10 22:12:43 +02:00
davide d5a61c15b6 aggiunge esercizio 39 2026-04-10 12:19:30 +02:00
davide 411696fc15 aggiunge esercizio 38 2026-04-09 21:19:57 +02:00
davide 8a3b5fb43b aggiunge esercizio 37 2026-04-09 20:59:27 +02:00
davide f56ffb7776 aggiunge esercizio 36 2026-04-09 19:58:47 +02:00
davide 1a2c044fb9 aggiunge esercizio 35 2026-04-09 18:54:38 +02:00
davide ec89c94373 aggiunge esercizio 34 2026-04-09 16:01:24 +02:00
davide 934f3096e7 aggiunge esercizio 33 2026-04-09 12:24:25 +02:00
davide 510d65e2ba aggiunge esercizio 32 2026-04-09 11:57:35 +02:00
davide 23ee9ea2bd aggiunge esercizio 31 2026-04-09 10:05:25 +02:00
davide 2b0f8a20d0 aggiunge esercizio 30 2026-04-09 09:57:20 +02:00
davide 54f0947b5e aggiunge esercizio 29 2026-04-09 09:32:01 +02:00
davide b838d9bb42 aggiunge esercizio 28 2026-04-09 09:05:37 +02:00
davide d719078b72 aggiunge esercizio 27 2026-04-08 19:23:54 +02:00
davide 752b04b4fe aggiunge esercizio 26 2026-04-08 18:09:57 +02:00
davide f35db81e06 aggiunge esercizio 25 2026-04-08 17:56:49 +02:00
davide 722a209308 aggiunge esercizio 24 2026-04-08 17:38:47 +02:00
davide f73731350e aggiunge esercizio 23 2026-04-08 16:08:57 +02:00
davide 73bcfd2e0e aggiunge esercizio 22 2026-04-08 15:42:46 +02:00
davide 8db7d11975 aggiunge esercizio 21 2026-04-08 14:50:39 +02:00
davide afcbed5d16 aggiunge esercizio 20 2026-04-08 14:28:04 +02:00
davide a9a5c4b7cb aggiunge esercizio 19 2026-04-08 13:50:35 +02:00
davide 80e5d42c7a aggiunge esercizio 18 2026-04-08 13:37:02 +02:00
davide 3e220720fa aggiunge esercizio 17 2026-04-08 12:14:42 +02:00
davide f05f115ccb aggiunge esercizio 16 2026-04-08 12:06:08 +02:00
39 changed files with 901 additions and 0 deletions
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+17
View File
@@ -0,0 +1,17 @@
user_word = input("Inserisci una parola: ")
user_word = user_word.upper()
for letter in user_word:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
else:
print(letter)
+20
View File
@@ -0,0 +1,20 @@
word_without_vowels =""
parola_utente = input("Inserisci una parola: ")
parola_utente = parola_utente.upper()
for letter in parola_utente:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
word_without_vowels += letter
print(word_without_vowels)
+10
View File
@@ -0,0 +1,10 @@
blocchi = int(input("Quanti blocchi hai? "))
strati = 0
blocchi_usati = 0
while blocchi_usati + strati + 1 <= blocchi:
strati += 1
blocchi_usati += strati
print("L'altezza della piramide è", strati, "usando", blocchi_usati, "blocchi")
+14
View File
@@ -0,0 +1,14 @@
c0 = int(input("Inserire un numero intero positivo: "))
passi=0
while c0 > 1:
if c0 % 2 == 0:
c0 /= 2
else:
c0 = c0*3+1
passi += 1
print("passi", passi)
+15
View File
@@ -0,0 +1,15 @@
hat_list = [1, 2, 3, 4, 5]
# passo 1
hat_list[2] = int(input("Inserisci il nuovo numero centrale: "))
# passo 2
del hat_list[-1]
# passo 3
print("Lunghezza: ",len(hat_list))
print(hat_list)
+36
View File
@@ -0,0 +1,36 @@
# passo 1
beatles = []
print("Passo 1:", beatles)
# passo 2
beatles.append("John")
beatles.append("Lennon")
beatles.append("Paul")
beatles.append("McCartney")
beatles.append("Geaorge Harrison")
print("passo 2:", beatles)
# passo 3
for i in range(2):
j = input("Inserici un altro membro: ")
beatles.append(j)
print("Passo 3", beatles)
# passo 4
for i in range(2):
del beatles[-1]
print("Passo 4", beatles)
# passo 5
beatles.insert(0, "Ringo Starr")
print("Passo 5", beatles)
+12
View File
@@ -0,0 +1,12 @@
my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]
unique_list = []
for number in my_list:
if number not in unique_list:
unique_list.append(number)
my_list = unique_list
print("The list with unique elements only:")
print(my_list)
+19
View File
@@ -0,0 +1,19 @@
def is_year_leap(year):
if year % 4 == 0:
return True
else:
return False
test_data = [1901, 2000, 2016, 1987]
test_result = [False, True, True, False]
for i in range(len(test_data)):
yr = test_data[i]
print(yr, "->", end="")
resutl = is_year_leap(yr)
if resutl == test_result[i]:
print("OK")
else:
print("Failed")
+31
View File
@@ -0,0 +1,31 @@
# from lab23 import is_year_leap
def is_year_leap(year):
if year % 4 == 0:
return True
else:
return False
def days_in_month(year, month):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_year_leap(year) == True:
days[1] = 29
return days[month - 1]
test_years = [1901, 2000, 2016, 1987]
test_months = [2, 2, 1, 11]
test_results = [28, 29, 31, 30]
for i in range(len(test_years)):
yr = test_years[i]
mo = test_months[i]
print(yr, mo, "->", end="")
result = days_in_month(yr, mo)
if result == test_results[i]:
print("OK")
else:
print("Failed")
+35
View File
@@ -0,0 +1,35 @@
def is_year_leap(year):
if year % 4 == 0:
return True
else:
return False
def days_in_month(year, month):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_year_leap(year) == True:
days[1] = 29
return days[month - 1]
def day_of_year(year, month, day):
if month < 1 or month > 12:
return None
elif day < 1 or day > 31:
return None
elif day > 29 and is_year_leap(year) == True and month == 2:
return None
elif day > 28 and is_year_leap(year) == False and month == 2:
return None
day_ = day
for i in range(1,month):
mo = days_in_month(year,i)
day_ += mo
return day_
print(day_of_year(2001,2,29))
+18
View File
@@ -0,0 +1,18 @@
def is_prime(num):
div = []
if num is float:
return None
for i in range(1,num+1):
if num % i == 0:
div.append(i)
if len(div) == 2:
return num
for i in range(1,20):
if is_prime(i+1):
print(i+1,end=" ")
print()
+41
View File
@@ -0,0 +1,41 @@
# conversioni
# 1 miglio = 1609.344 metri
# 1 gallone = 3.785411784 litri
def liters_100km_to_miles_gallon(litres):
"""converte l/100km in miglia per gallone"""
if litres < 0:
return None
gallons_k = litres / 3.785411784 # per 100 km
gallons_m = gallons_k / 100 # per 1 km
gallons_m = gallons_m * 1.609344 # per 1 mi
gallons = gallons_m ** (-1)
return gallons
def miles_gallon_to_liters_100km(miles):
"""converte miglia per gallone in l/100km"""
chilometers = miles * 1.609344 # con un gallone
chilometers_l = chilometers / 3.785411784 # con un litro
chilometers_100 = chilometers_l / 100 # 100 km per L
liters_100 = chilometers_100 ** (-1)
return liters_100
print(liters_100km_to_miles_gallon(3.9))
print(liters_100km_to_miles_gallon(7.5))
print(liters_100km_to_miles_gallon(10.))
print(miles_gallon_to_liters_100km(60.3))
print(miles_gallon_to_liters_100km(31.4))
print(miles_gallon_to_liters_100km(23.5))
+20
View File
@@ -0,0 +1,20 @@
def mysplit(string):
words = []
word = ""
for char in string:
if char != " ":
word += char
else:
if word:
words.append(word)
word = ""
if word:
words.append(word)
return words
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
+22
View File
@@ -0,0 +1,22 @@
number = input("Inserisci un numero: ")
digits = [
["###", "# #", "# #", "# #", "###"], # 0
[" #", " #", " #", " #", " #"], # 1
["###", " #", "###", "# ", "###"], # 2
["###", " #", "###", " #", "###"], # 3
["# #", "# #", "###", " #", " #"], # 4
["###", "# ", "###", " #", "###"], # 5
["###", "# ", "###", "# #", "###"], # 6
["###", " #", " #", " #", " #"], # 7
["###", "# #", "###", "# #", "###"], # 8
["###", "# #", "###", " #", "###"], # 9
]
for row in range(5):
line = ""
for ch in number:
digit_index = int(ch)
segment = digits[digit_index][row]
line = line + segment + " "
print(line)
+47
View File
@@ -0,0 +1,47 @@
def cifra(messaggio, shift):
"""
Cifra il messaggio usando il cifrario di Cesare con lo spostamento dato.
- Lettere minuscole rimangono minuscole
- Lettere maiuscole rimangono maiuscole
- Caratteri non alfabetici (spazi, numeri, punteggiatura) rimangono invariati
"""
risultato = ""
for c in messaggio:
if c.islower():
base = ord('a')
codice = ord(c)
nuovo_codice = (codice - base + shift) % 26 + base
cifrato = chr(nuovo_codice)
calcolo = f"({codice} - {base} + {shift}) % 26 + {base} = {nuovo_codice}"
elif c.isupper():
base = ord('A')
codice = ord(c)
nuovo_codice = (codice - base + shift) % 26 + base
cifrato = chr(nuovo_codice)
calcolo = f"({codice} - {base} + {shift}) % 26 + {base} = {nuovo_codice}"
else:
cifrato = c
risultato += cifrato
return risultato
messaggio = input("Inserire un messaggio da cifrare: ")
shift = 0
while shift < 1 or shift > 25:
try:
shift = int(input("Inserire il valore di spostamento (1-25): "))
if shift < 1 or shift > 25:
print("Valore fuori intervallo. Inserire un numero tra 1 e 25.")
except ValueError:
print("Input non valido. Inserire un numero intero.")
testo_cifrato = cifra(messaggio, shift)
print(f"Messaggio cifrato: {testo_cifrato}")
+15
View File
@@ -0,0 +1,15 @@
iban = input("Inserisci un iban valido: ")
iban_ruotato = iban[4:]+iban[:4]
iban_numerico = ""
for c in iban_ruotato:
if c.isalpha():
iban_numerico += str(ord(c)-ord("A") + 10)
else:
iban_numerico += c
if int(iban_numerico) % 97 == 1:
print("Iban valido")
else:
print("Iban non valido")
+14
View File
@@ -0,0 +1,14 @@
def anagramma(parola1, parola2):
parola_1 = list(parola1)
parola_2 = list(parola2)
if sorted(parola_1) == sorted(parola_2):
print("Anagrami")
else:
print("Non anagrammi")
parola_uno = input("Inserisci 1 parola: ")
parola_due = input("Inserisci 2 parola: ")
anagramma(parola_uno, parola_due)
+17
View File
@@ -0,0 +1,17 @@
data = input("Inserisci la tua data di nascita (formato AAAA MM GG): ")
data_raw = data.replace(" ","")
def somma_data(data_da_sommare):
data = 0
for ch in data_da_sommare:
data += int(ch)
return data
a = somma_data(data_raw)
while a >= 10:
a = somma_data(str(a))
print("La cifra della vita è:", a)
+15
View File
@@ -0,0 +1,15 @@
str1 = input("Inserire la prima stringa: ")
str2 = input("Inserire la seconda stringa: ")
pos = 0
for ch in str1:
lettera = str2.find(ch, pos)
if lettera == -1:
print("No")
break
pos = lettera + 1
else:
print("Si")
+34
View File
@@ -0,0 +1,34 @@
print("Inserire le righe per verificare la validità del sudoku")
S = []
for i in range(9):
riga = input("Inserire riga: ")
riga_n = [int(c) for c in riga]
S.append(riga_n)
status = True
for j in range(9):
riga = S[j]
for n in range(1, 10):
if n not in riga:
status = False
for k in range(9):
colonna = [S[r][k] for r in range(9)]
for n in range(1, 10):
if n not in colonna:
status = False
for r in range(0, 9, 3):
for c in range(0, 9, 3):
quadrato = [S[r+dr][c+dc] for dr in range(3) for dc in range(3)]
for n in range(1, 10):
if n not in quadrato:
status = False
if status == True:
print("Si")
else:
print("No")
+32
View File
@@ -0,0 +1,32 @@
class Stack:
def __init__(self):
self.__stack_list = []
def push(self, val):
self.__stack_list.append(val)
def pop(self):
val = self.__stack_list[-1]
del self.__stack_list[-1]
return val
class CountingStack(Stack):
def __init__(self):
Stack.__init__(self)
self.__j = 0
def get_counter(self):
return self.__j
def pop(self):
self.__j += 1
return Stack.pop(self)
stk = CountingStack()
for i in range(100):
stk.push(i)
stk.pop()
print(stk.get_counter())
+27
View File
@@ -0,0 +1,27 @@
class QueueError(Exception):
pass
class Queue:
def __init__(self):
self.__queue_list = []
def put(self, val):
self.__queue_list.insert(0, val)
def get(self):
if len(self.__queue_list) < 1:
raise QueueError("Errore di coda")
return self.__queue_list.pop()
que = Queue()
que.put(1)
que.put("cane")
que.put(False)
try:
for i in range(4):
print(que.get())
except:
print("Errore di coda")
+34
View File
@@ -0,0 +1,34 @@
class QueueError(Exception):
pass
class Queue:
def __init__(self):
self.__queue_list = []
def put(self, val):
self.__queue_list.insert(0, val)
def get(self):
if len(self.__queue_list) < 1:
raise QueueError("Errore di coda")
return self.__queue_list.pop()
class SuperQueue(Queue):
def __init__(self):
Queue.__init__(self)
def isempty(self):
return len(self._Queue__queue_list) == 0
que = SuperQueue()
que.put(1)
que.put("cane")
que.put(False)
for i in range(4):
if not que.isempty():
print(que.get())
else:
print("Coda vuota")
+41
View File
@@ -0,0 +1,41 @@
def format_time(hh, mm, ss):
return f"{hh:02d}:{mm:02d}:{ss:02d}"
class Timer:
def __init__(self, hours, minutes, seconds):
self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds
def __str__(self):
return format_time(self.__hours, self.__minutes, self.__seconds)
def next_second(self):
self.__seconds += 1
if self.__seconds > 59:
self.__seconds = 0
self.__minutes += 1
if self.__minutes > 59:
self.__minutes = 0
self.__hours += 1
if self.__hours > 23:
self.__hours = 0
def prev_second(self):
self.__seconds -= 1
if self.__seconds < 0:
self.__seconds = 59
self.__minutes -= 1
if self.__minutes < 0:
self.__minutes = 59
self.__hours -= 1
if self.__hours < 0:
self.__hours = 23
timer = Timer(23, 59, 59)
print(timer)
timer.next_second()
print(timer)
timer.prev_second()
print(timer)
+36
View File
@@ -0,0 +1,36 @@
class WeekDayError(Exception):
pass
class Weeker:
__GIORNI = ['lun', 'mar', 'mer', 'gio', 'ven', 'sab', 'dom']
def __init__(self, day):
if day not in Weeker.__GIORNI:
raise WeekDayError("Giorno non valido: " + day)
self.__day_index = Weeker.__GIORNI.index(day)
def __str__(self):
return Weeker.__GIORNI[self.__day_index].capitalize()
def add_days(self, n):
self.__day_index = (self.__day_index + n) % 7
def subtract_days(self, n):
self.__day_index = (self.__day_index - n) % 7
# --- TEST ---
try:
weekday = Weeker('lun')
print(weekday)
weekday.add_days(15)
print(weekday)
weekday.subtract_days(23)
print(weekday)
weekday = Weeker('lunedì')
except WeekDayError:
print("Mi dispiace, non posso soddisfare la sua richiesta.")
+28
View File
@@ -0,0 +1,28 @@
import math
class Point:
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
def getx(self):
return self.__x
def gety(self):
return self.__y
def distance_from_xy(self, x, y):
return math.hypot(self.__x - x, self.__y - y)
def distance_from_point(self, point):
return self.distance_from_xy(point.getx(), point.gety())
# --- TEST ---
point1 = Point(0, 0)
point2 = Point(1, 1)
print(point1.distance_from_point(point2))
print(point2.distance_from_xy(2, 0))
+35
View File
@@ -0,0 +1,35 @@
import math
class Point:
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
def getx(self):
return self.__x
def gety(self):
return self.__y
def distance_from_xy(self, x, y):
return math.hypot(self.__x - x, self.__y - y)
def distance_from_point(self, point):
return self.distance_from_xy(point.getx(), point.gety())
class Triangle:
def __init__(self, vertice1, vertice2, vertice3):
self.__vertici = [vertice1, vertice2, vertice3]
def perimeter(self):
v = self.__vertici
lato1 = v[0].distance_from_point(v[1])
lato2 = v[1].distance_from_point(v[2])
lato3 = v[2].distance_from_point(v[0])
return lato1 + lato2 + lato3
triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
print(triangle.perimeter())
+31
View File
@@ -0,0 +1,31 @@
from os import strerror
file_name = "lab43.txt"
# Il dizionario conterra' una coppia chiave/valore per ogni lettera trovata:
# chiave = lettera, valore = quante volte appare nel file.
letters = {}
try:
stream = open(file_name, "rt", encoding="utf-8")
ch = stream.read(1)
while ch != "":
ch = ch.lower()
if "a" <= ch <= "z":
if ch in letters:
letters[ch] += 1
else:
letters[ch] = 1
ch = stream.read(1)
stream.close()
for letter in sorted(letters.keys()):
print(letter, "->", letters[letter])
except IOError as e:
print("Errore di I/O:", strerror(e.errno))
+1
View File
@@ -0,0 +1 @@
aBc
+36
View File
@@ -0,0 +1,36 @@
from os import strerror
file_name = "lab43.txt"
letters = {}
try:
source = open(file_name, "rt", encoding="utf-8")
ch = source.read(1)
while ch != "":
ch = ch.lower()
if "a" <= ch <= "z":
if ch in letters:
letters[ch] += 1
else:
letters[ch] = 1
ch = source.read(1)
source.close()
target = open(file_name + ".hist", "wt", encoding="utf-8")
for letter, counter in sorted(letters.items(), key=lambda item: item[1], reverse=True):
target.write(letter + " -> " + str(counter) + "\n")
target.close()
print("Istogramma salvato in:", file_name + ".hist")
except IOError as e:
print("Errore di I/O:", strerror(e.errno))
+64
View File
@@ -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))
+5
View File
@@ -0,0 +1,5 @@
John Smith 5
Anna Bolena 4,5
John Smith 2
Anna Bolena 11
Andrew Cox 1,5
+22
View File
@@ -0,0 +1,22 @@
import os
def find(path, dir):
if not os.path.isdir(path):
return
for name in os.listdir(path):
full_path = os.path.join(path, name)
if os.path.isdir(full_path):
if name == dir:
print(os.path.abspath(full_path))
find(full_path, dir)
if __name__ == "__main__":
start_path = input("Percorso di partenza: ")
directory_name = input("Directory da cercare: ")
find(start_path, directory_name)
+28
View File
@@ -0,0 +1,28 @@
from datetime import datetime
d = datetime(year=2020, month=11, day=4, hour=14, minute=53, second=0)
# Direttive usate con strftime:
# %Y anno con 4 cifre -> 2020
# %y anno con 2 cifre -> 20
# %m mese numerico -> 11
# %B nome mese completo -> November
# %b nome mese abbreviato -> Nov
# %d giorno del mese -> 04
# %H ora formato 24h -> 14
# %M minuti -> 53
# %S secondi -> 00
# %p AM/PM -> PM
# %a giorno abbreviato -> Wed
# %A giorno completo -> Wednesday
# %w giorno settimana -> 3
# %j giorno dell'anno -> 309
# %W numero settimana -> 44
print(d.strftime("%Y/%m/%d %H:%M:%S"))
print(d.strftime("%y/%B/%d %H:%M:%S %p"))
print(d.strftime("%a, %Y %b %d"))
print(d.strftime("%A, %Y %B %d"))
print(d.strftime("Weekday: %w"))
print(d.strftime("Day of the year: %j"))
print(d.strftime("Week number of the year: %W"))
+29
View File
@@ -0,0 +1,29 @@
from calendar import Calendar
class MyCalendar(Calendar):
def count_weekday_in_year(self, year, weekday):
count = 0
for month in range(1, 13):
month_calendar = self.monthdays2calendar(year, month)
for week in month_calendar:
for day_number, day_weekday in week:
if day_number != 0 and day_weekday == weekday:
count += 1
return count
my_calendar = MyCalendar()
result = my_calendar.count_weekday_in_year(2000, 6)
print(result)