Es. Python tutorial - Librerie standard
Versione italiana
Esercizi
1. Utilizzo di datetime
per calcolare
l’età
Scrivi una funzione che, data una data di nascita nel formato
YYYY-MM-DD
, calcoli l’età attuale della persona.
2. Conteggio delle parole in un testo con
collections.Counter
Utilizza collections.Counter
per contare quante volte
appare ogni parola in una stringa di testo.
3. Generazione di tutte le combinazioni di una lista con
itertools.combinations
Data una lista di elementi, genera tutte le combinazioni possibili di due elementi.
4. Validazione di un indirizzo email con
re
Scrivi una funzione che verifichi se una stringa è un indirizzo email valido utilizzando le espressioni regolari.
5. Creazione di una nuova directory con
os
Scrivi un programma che crei una nuova directory chiamata
nuova_cartella
nel percorso corrente.
6. Copia di un file con shutil
Scrivi un programma che copi un file chiamato
origine.txt
in una nuova destinazione chiamata
copia.txt
.
7. Esecuzione di un comando di sistema con
subprocess
Utilizza il modulo subprocess
per eseguire il comando di
sistema che elenca i file nella directory corrente.
8. Calcolo della differenza tra due date con
datetime
Scrivi una funzione che calcoli il numero di giorni tra due date
fornite nel formato YYYY-MM-DD
.
9. Utilizzo di defaultdict
per raggruppare
elementi
Utilizza collections.defaultdict
per raggruppare una
lista di tuple (categoria, elemento) in un dizionario dove le chiavi
sono le categorie e i valori sono liste di elementi.
10. Generazione di permutazioni di una stringa con
itertools.permutations
Scrivi un programma che generi tutte le permutazioni possibili dei caratteri in una stringa data.
Soluzioni
# 1. Utilizzo di `datetime` per calcolare l'età
from datetime import datetime
def calcola_eta(data_nascita):
= datetime.strptime(data_nascita, "%Y-%m-%d")
data_nascita = datetime.now()
oggi = oggi.year - data_nascita.year
eta if oggi.month < data_nascita.month or (oggi.month == data_nascita.month and oggi.day < data_nascita.day):
-= 1
eta return eta
# Esempio d'uso:
print(calcola_eta("1990-05-15")) # Output: età attuale
# 2. Conteggio delle parole in un testo con `collections.Counter`
from collections import Counter
def conta_parole(testo):
= testo.split()
parole = Counter(parole)
conteggio return conteggio
# Esempio d'uso:
= "ciao mondo ciao a tutti"
testo print(conta_parole(testo)) # Output: Counter({'ciao': 2, 'mondo': 1, 'a': 1, 'tutti': 1})
# 3. Generazione di tutte le combinazioni di una lista con `itertools.combinations`
from itertools import combinations
def genera_combinazioni(lista):
return list(combinations(lista, 2))
# Esempio d'uso:
= [1, 2, 3]
lista print(genera_combinazioni(lista)) # Output: [(1, 2), (1, 3), (2, 3)]
# 4. Validazione di un indirizzo email con `re`
import re
def email_valida(email):
= r'^[\w\.-]+@[\w\.-]+\.\w+$'
pattern return re.match(pattern, email) is not None
# Esempio d'uso:
print(email_valida("esempio@dominio.com")) # Output: True
print(email_valida("esempio@dominio")) # Output: False
# 5. Creazione di una nuova directory con `os`
import os
def crea_directory(nome_cartella):
os.mkdir(nome_cartella)
# Esempio d'uso:
"nuova_cartella")
crea_directory(
# 6. Copia di un file con `shutil`
import shutil
def copia_file(orig, dest):
shutil.copy(orig, dest)
# Esempio d'uso:
"origine.txt", "copia.txt")
copia_file(
# 7. Esecuzione di un comando di sistema con `subprocess`
import subprocess
def esegui_comando(comando):
= subprocess.run(comando, shell=True, capture_output=True, text=True)
risultato return risultato.stdout
# Esempio d'uso:
print(esegui_comando("ls")) # Su Unix/Linux
# print(esegui_comando("dir")) # Su Windows
# 8. Calcolo della differenza tra due date con `datetime`
from datetime import datetime
def differenza_giorni(data1, data2):
= datetime.strptime(data1, "%Y-%m-%d")
data1 = datetime.strptime(data2, "%Y-%m-%d")
data2 = data2 - data1
differenza return differenza.days
# Esempio d'uso:
print(differenza_giorni("2023-01-01", "2023-12-31")) # Output: 364
# 9. Utilizzo di `defaultdict` per raggruppare elementi
from collections import defaultdict
def raggruppa_elementi(lista):
= defaultdict(list)
dizionario for categoria, elemento in lista:
dizionario[categoria].append(elemento)return dizionario
# Esempio d'uso:
= [("frutta", "mela"), ("verdura", "carota"), ("frutta", "banana")]
lista print(raggruppa_elementi(lista)) # Output: {'frutta': ['mela', 'banana'], 'verdura': ['carota']}
# 10. Generazione di permutazioni di una stringa con `itertools.permutations`
from itertools import permutations
def genera_permutazioni(stringa):
= permutations(stringa)
perm return [''.join(p) for p in perm]
# Esempio d'uso:
print(genera_permutazioni("abc")) # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
English version
Exercises
1. Using datetime
to calculate age
Write a function that, given a birth date in the format
YYYY-MM-DD
, calculates the person’s current age.
2. Counting words in a text with
collections.Counter
Use collections.Counter
to count how many times each
word appears in a text string.
3. Generating all combinations of a list with
itertools.combinations
Given a list of elements, generate all possible combinations of two elements.
4. Validating an email address with
re
Write a function that checks whether a string is a valid email address using regular expressions.
5. Creating a new directory with os
Write a program that creates a new directory called
new_folder
in the current path.
6. Copying a File with shutil
Write a program that copies a file called source.txt
to
a new destination called copy.txt
.
7. Running a System Command with
subprocess
Use the subprocess
module to run the system command that
lists the files in the current directory.
8. Calculating the Difference Between Two Dates with
datetime
Write a function that calculates the number of days between two dates
given in the format YYYY-MM-DD
.
9. Using defaultdict
to Group
Elements
Use collections.defaultdict
to group a list of tuples
(category, element) into a dictionary where the keys are the categories
and the values are lists of elements.
10. Generating Permutations of a String with
itertools.permutations
Write a program that generates all possible permutations of the characters in a given string.
Solutions
# 1. Using `datetime` to calculate age
from datetime import datetime
def calculate_age(birthdate):
= datetime.strptime(birthdate, "%Y-%m-%d")
birthdate = datetime.now()
today = today.year - birthdate.year
age if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
-= 1
age return age
# Example usage:
print(calculate_age("1990-05-15")) # Output: current age
# 2. Counting words in a text with `collections.Counter`
from collections import Counter
def wordcount(text):
= text.split()
words = Counter(words)
count return count
# Example of use:
= "hello world hello everyone"
text print(wordcount(text)) # Output: Counter({'hello': 2, 'world': 1, 'a': 1, 'everyone': 1})
# 3. Generate all combinations of a list with `itertools.combinations`
from itertools import combinations
def generate_combinations(list):
return list(combinations(list, 2))
# Example of use:
list = [1, 2, 3]
print(genera_combinations(list)) # Output: [(1, 2), (1, 3), (2, 3)]
# 4. Validate an email address with `re`
import re
def email_valida(email):
= r'^[\w\.-]+@[\w\.-]+\.\w+$'
pattern return re.match(pattern, email) is not None
# Example usage:
print(valid_email("example@domain.com")) # Output: True
print(valid_email("example@domain")) # Output: False
# 5. Creating a new directory with `os`
import os
def create_directory(folder_name):
os.mkdir(folder_name)
# Example usage:
"new_directory")
create_directory(
# 6. Copying a file with `shutil`
import shutil
def copy_file(orig, dest):
shutil.copy(orig, dest)
# Example usage:
"source.txt", "copy.txt")
copy_file(
# 7. Running a system command with `subprocess`
import subprocess
def run_command(command):
= subprocess.run(command, shell=True, capture_output=True, text=True)
result return result.stdout
# Example usage:
print(run_command("ls")) # On Unix/Linux
# print(run_command("dir")) # On Windows
# 8. Calculating the difference between two dates with `datetime`
from datetime import datetime
def difference_days(date1, date2):
= datetime.strptime(date1, "%Y-%m-%d")
date1 = datetime.strptime(date2, "%Y-%m-%d")
date2 = date2 - date1
difference return difference.days
# Example usage:
print(difference_days("2023-01-01", "2023-12-31")) # Output: 364
# 9. Using `defaultdict` to group items
from collections import defaultdict
def group_items(list):
= defaultdict(list)
dictionary for category, item in list:
dictionary[category].append(item)return dictionary
# Example usage:
list = [("fruit", "apple"), ("vegetable", "carrot"), ("fruit", "banana")]
print(group_items(list)) # Output: {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
# 10. Generating permutations of a string with `itertools.permutations`
from itertools import permutations
def generate_permutations(string):
= permutations(string)
perm return [''.join(p) for p in perm]
# Example usage:
print(generate_permutations("abc")) # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Commenti
Posta un commento