Es. Python tutorial - Librerie standard 2

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

Es. Python tutorial - Librerie standard 2

Versione italiana

Esercizi

1. Formattazione di una data con datetime.strftime
Scrivi una funzione che accetti una data nel formato YYYY-MM-DD e la restituisca formattata come DD/MM/YYYY.

2. Conta i caratteri univoci in una stringa con collections.Counter
Scrivi una funzione che prenda una stringa e restituisca un dizionario con il conteggio di ogni carattere univoco.

3. Generazione del prodotto cartesiano di due liste con itertools.product
Data due liste, genera tutte le possibili coppie combinando un elemento della prima lista con un elemento della seconda.

4. Estrazione di numeri da una stringa con re.findall
Scrivi una funzione che estragga tutti i numeri presenti in una stringa.

5. Ottenere il percorso assoluto di un file con os.path.abspath
Scrivi una funzione che restituisca il percorso assoluto di un file dato il suo nome.

6. Compressione di un file con shutil.make_archive
Scrivi un programma che crei un archivio .zip a partire da una cartella esistente.

7. Esecuzione di un comando con output in tempo reale usando subprocess.Popen
Scrivi un programma che esegua ping google.com (o un comando simile) e stampi l’output riga per riga mentre viene generato.

8. Calcolo dell’ora attuale in un altro fuso orario con datetime
Scrivi una funzione che restituisca l’ora attuale a New York (America/New_York).

9. Creazione di un OrderedDict per mantenere l’ordine degli elementi
Scrivi una funzione che accetti una lista di tuple (chiave, valore) e restituisca un dizionario ordinato secondo l’ordine di inserimento.

10. Generazione di una sequenza infinita con itertools.count
Scrivi una funzione che generi numeri interi a partire da un valore iniziale con un passo definito.


Soluzioni

# 1. Formattazione di una data con `datetime.strftime`
from datetime import datetime

def formatta_data(data):
    dt = datetime.strptime(data, "%Y-%m-%d")
    return dt.strftime("%d/%m/%Y")

print(formatta_data("2025-02-15"))  # Output: "15/02/2025"

# 2. Conta i caratteri univoci in una stringa con `collections.Counter`
from collections import Counter

def conta_caratteri(stringa):
    return dict(Counter(stringa))

print(conta_caratteri("banana"))  # Output: {'b': 1, 'a': 3, 'n': 2}

# 3. Generazione del prodotto cartesiano con `itertools.product`
from itertools import product

def prodotto_cartesiano(lista1, lista2):
    return list(product(lista1, lista2))

print(prodotto_cartesiano([1, 2], ['A', 'B']))  # Output: [(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

# 4. Estrazione di numeri da una stringa con `re.findall`
import re

def estrai_numeri(testo):
    return re.findall(r'\d+', testo)

print(estrai_numeri("Il numero 42 è seguito da 2025"))  # Output: ['42', '2025']

# 5. Ottenere il percorso assoluto di un file con `os.path.abspath`
import os

def percorso_assoluto(nome_file):
    return os.path.abspath(nome_file)

print(percorso_assoluto("test.txt"))  # Output: Percorso assoluto del file

# 6. Compressione di un file con `shutil.make_archive`
import shutil

def comprimi_cartella(cartella, nome_output):
    shutil.make_archive(nome_output, 'zip', cartella)

# Esempio d'uso:
# comprimi_cartella("cartella_da_comprimere", "archivio")

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

def esegui_ping():
    processo = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE, text=True)
    for riga in processo.stdout:
        print(riga.strip())

# esegui_ping()  # Da eseguire solo se necessario

# 8. Calcolo dell'ora attuale in un altro fuso orario con `datetime`
from datetime import datetime
import pytz

def ora_new_york():
    fuso_orario = pytz.timezone("America/New_York")
    ora_attuale = datetime.now(fuso_orario)
    return ora_attuale.strftime("%Y-%m-%d %H:%M:%S")

# print(ora_new_york())  # Output: Ora corrente a New York

# 9. Creazione di un `OrderedDict` per mantenere l'ordine degli elementi
from collections import OrderedDict

def crea_dizionario_ordinato(lista_tupla):
    return OrderedDict(lista_tupla)

print(crea_dizionario_ordinato([("a", 1), ("b", 2), ("c", 3)]))  
# Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# 10. Generazione di una sequenza infinita con `itertools.count`
from itertools import count

def genera_numeri(start, step):
    generatore = count(start=start, step=step)
    return [next(generatore) for _ in range(5)]

print(genera_numeri(10, 2))  # Output: [10, 12, 14, 16, 18]

English version

Exercises

1. Formatting a date with datetime.strftime

Write a function that takes a date in the format YYYY-MM-DD and returns it formatted as DD/MM/YYYY.

2. Count the unique characters in a string with collections.Counter

Write a function that takes a string and returns a dictionary with the count of each unique character.

3. Generating the Cartesian product of two lists with itertools.product

Given two lists, generate all possible pairs by combining an element of the first list with an element of the second.

4. Extracting numbers from a string with re.findall

Write a function that extracts all the numbers present in a string.

5. Getting the absolute path of a file with os.path.abspath Write a function that returns the absolute path of a file given its name.

6. Compressing a file with shutil.make_archive Write a program that creates a .zip archive from an existing folder.

7. Running a command with real-time output using subprocess.Popen Write a program that executes ping google.com (or a similar command) and prints the output line by line as it is generated.

8. Calculating the current time in another time zone with datetime Write a function that returns the current time in New York (America/New_York).

9. Creating an OrderedDict to maintain the order of the elements Write a function that accepts a list of tuples (key, value) and returns a dictionary sorted according to the insertion order.

10. Generating an infinite sequence with itertools.count Write a function that generates integers starting from an initial value with a defined step.


Solutions

# 1. Formatting a date with `datetime.strftime`
from datetime import datetime

def format_date(date):
dt = datetime.strptime(date, "%Y-%m-%d")
return dt.strftime("%d/%m/%Y")

print(format_date("2025-02-15")) # Output: "15/02/2025"

# 2. Count unique characters in a string with `collections.Counter`
from collections import Counter

def char_count(string):
return dict(Counter(string))

print(char_count("banana")) # Output: {'b': 1, 'a': 3, 'n': 2}

# 3. Generating the product cartesian with `itertools.product`
from itertools import product

def cartesian_product(list1, list2):
return list(product(list1, list2))

print(cartesian_product([1, 2], ['A', 'B'])) # Output: [(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

# 4. Extracting numbers from a string with `re.findall`
import re

def extract_numbers(text):
return re.findall(r'\d+', text)

print(extract_numbers("The number 42 is followed by 2025")) # Output: ['42', '2025']

# 5. Getting the absolute path of a file with `os.path.abspath`
import os

def absolute_path(file_name):
return os.path.abspath(file_name)

print(abspath("test.txt")) # Output: Absolute path to the file

# 6. Compressing a file with `shutil.make_archive`
import shutil

def compress_folder(folder, output_name):
shutil.make_archive(output_name, 'zip', folder)

# Example usage:
# compress_folder("folder_to_compress", "archive")

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

def run_ping():
process = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE, text=True)
for line in process.stdout:
print(line.strip())

# run_ping() # Only run if necessary

# 8. Calculating the current time in another time zone with `datetime`
from datetime import datetime
import pytz

def newyorktime():
timezone = pytz.timezone("America/New_York")
currenttime = datetime.now(timezone)
return currenttime.strftime("%Y-%m-%d %H:%M:%S")

# print(newyorktime()) # Output: Current time in New York

# 9. Creating an `OrderedDict` to maintain the order of the elements
from collections import OrderedDict

def create_ordered_dictionary(tuple_list):
return OrderedDict(tuple_list)

print(create_ordered_dictionary([("a", 1), ("b", 2), ("c", 3)]))
# Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# 10. Generating an infinite sequence with `itertools.count`
from itertools import count

def generate_numbers(start, step):
generator = count(start=start, step=step)
return [next(generator) for _ in range(5)]

print(generate_numbers(10, 2)) # Output: [10, 12, 14, 16, 18]

Commenti