Es. Python tutorial - Librerie standard

Es. Python tutorial - Librerie standard Es. Python tutorial - Librerie standard

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):
    data_nascita = datetime.strptime(data_nascita, "%Y-%m-%d")
    oggi = datetime.now()
    eta = oggi.year - data_nascita.year
    if oggi.month < data_nascita.month or (oggi.month == data_nascita.month and oggi.day < data_nascita.day):
        eta -= 1
    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):
    parole = testo.split()
    conteggio = Counter(parole)
    return conteggio

# Esempio d'uso:
testo = "ciao mondo ciao a tutti"
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:
lista = [1, 2, 3]
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):
    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    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:
crea_directory("nuova_cartella")

# 6. Copia di un file con `shutil`
import shutil

def copia_file(orig, dest):
    shutil.copy(orig, dest)

# Esempio d'uso:
copia_file("origine.txt", "copia.txt")

# 7. Esecuzione di un comando di sistema con `subprocess`
import subprocess

def esegui_comando(comando):
    risultato = subprocess.run(comando, shell=True, capture_output=True, text=True)
    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):
    data1 = datetime.strptime(data1, "%Y-%m-%d")
    data2 = datetime.strptime(data2, "%Y-%m-%d")
    differenza = data2 - data1
    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):
    dizionario = defaultdict(list)
    for categoria, elemento in lista:
        dizionario[categoria].append(elemento)
    return dizionario

# Esempio d'uso:
lista = [("frutta", "mela"), ("verdura", "carota"), ("frutta", "banana")]
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):
    perm = permutations(stringa)
    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):
birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
today = datetime.now()
age = today.year - birthdate.year
if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
age -= 1
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):
words = text.split()
count = Counter(words)
return count

# Example of use:
text = "hello world hello everyone"
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):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
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:
create_directory("new_directory")

# 6. Copying a file with `shutil`
import shutil

def copy_file(orig, dest):
shutil.copy(orig, dest)

# Example usage:
copy_file("source.txt", "copy.txt")

# 7. Running a system command with `subprocess`
import subprocess

def run_command(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
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):
date1 = datetime.strptime(date1, "%Y-%m-%d")
date2 = datetime.strptime(date2, "%Y-%m-%d")
difference = date2 - date1
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):
dictionary = defaultdict(list)
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):
perm = permutations(string)
return [''.join(p) for p in perm]

# Example usage:
print(generate_permutations("abc")) # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Commenti