Skip to content

Instantly share code, notes, and snippets.

@Steffo99
Last active January 19, 2022 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Steffo99/b9eaf8649fe0e341ae0cdbd78b0a9055 to your computer and use it in GitHub Desktop.
Save Steffo99/b9eaf8649fe0e341ae0cdbd78b0a9055 to your computer and use it in GitHub Desktop.
Ripasso di Python con Kappa
# Evita di usare assert così, non è il motivo per cui è stato inventato
def assicurati_che_sia_positivo(numero):
assert numero > 0, "Il numero è negativo o zero"
# Il modo giusto è questo
def assicurati_che_sia_positivo(numero):
if numero > 0:
raise Exception("Il numero è negativo o zero")
class DiziosetIterativo(dict):
"""
Questo dizioset implementa unione e intersezione per side-effects, modificando sè stesso.
"""
def unione(self,other):
for k in other.keys():
if k not in self:
self[k]=other[k]
def intersezione(self,other):
for k in other.keys():
if k in self:
self.pop(k)
class DiziosetUpdate(dict):
"""
Questo dizioset implementa unione usando :meth:`dict.update`.
"""
def unione(self, other):
self.update(other)
class DiziosetOr(dict):
"""
Solo Python ^3.9: questo dizioset implementa unione "pura" tramite l'operatore bitwise or ``|`` .
"""
def unione(self, other):
return self | other
class DiziosetOr(dict):
"""
Solo Python ^3.9: questo dizioset implementa unione in-place tramite l'operatore bitwise or inplace ``|=`` .
"""
def unione(self, other):
self |= other
class DiziosetComprehension(dict):
"""
Questo dizioset implementa unione e intersezione tramite funzioni pure, utilizzando dict comprehension.
"""
def unione(self, other):
return {**self, **other}
def intersezione(self, other):
return {key: value for key, value in other if key in self}
# Iteratore
# è una sequenza di valori
# 1, 2, 3, 4...
# 1, 3, 5, 7...
# "S", "T", "E", "F", "F", "O"
steffo = iter(["S", "T", "E", "F", "F", "O"])
pari_sotto_10 = [2, 4, 6, 8].__iter__
for lettera in iter(["A", "B", "C"]):
...
# Generatore
# è una funzione che crea iteratori
def iter_primi5_multipli(i):
return iter([i * n for n in range(5)])
def iter_infiniti_multipli(i):
n = 0
while True:
n += 1
yield n * i
class InfinitiMultipli:
def __init__(self, i):
self.i = i
self.n = 0
def __next__(self):
self.n += 1
return self.n * self.i
# Una vera coroutine
# Non è parte del programma di esame, la terminologia di Leoncini è sbagliata!!!
import asyncio
async def coroutine():
print("Qualcosa.")
await asyncio.sleep(1)
print("Qualcos'altro, un secondo dopo.")
# Esercizio
# Realizzare un iterabile per la sequenza di numeri a*i + b
def esercizio_funzione(a, b, n):
"""
Generatore che crea un iteratore che risolve l'esercizio!
"""
cache = []
# Pre-calcoliamo i primi n valori
i = 0
while len(cache) < n:
cache.append(a * i + b)
i += 1
# Iniziamo a restituirli
while True:
# Quando scendono sotto il valore di n...
if len(cache) < (n/2):
# Precalcoliamo altri valori, finchè non ne abbiamo n
while len(cache) < n:
cache.append(a * i + b)
i += 1
yield cache.pop(0)
class EsercizioClasse:
"""
Classe che funziona da iteratore per risolvere l'esercizio!
"""
def __init__(self, a, b, n) -> None:
self.a = a
self.b = b
self.n = n
self.i = 0
self.cache = []
self.precalcolo()
def precalcolo(self):
"""
Pre-calcola valori finchè non ce ne sono n in cache.
"""
while len(self.cache) < self.n:
self.cache.append(self.a * self.i + self.b)
self.i += 1
def __next__(self):
"""
Calcola il prossimo valore.
"""
if len(self.cache) < (self.n / 2):
self.precalcolo()
return self.cache.pop(0)
iteratore1 = esercizio_funzione(a=1, b=2, n=10)
iteratore2 = EsercizioClasse(a=1, b=2, n=10)
"""
Esercizio 1) Implementare una metaclasse mymeta con le carateristiche de-
scritte di seguito:
1. Se pwd protected è una classe di tipo mymeta, appena pwd protected
viene definita l'utente riceve un messaggio in cui viene chiesto (due
volte, con conferma) di digitare una nuova password.
2. Ogni volta che il programma istanzia la classe pwd protected, all'utente
viene chiesto di digitare la password.
3. Se la password è errata l'oggetto non deve essere creato e deve
essere visualizzato un opportuno messaggio di errore.
Si possono ignorare (senza alcuna penalizzazione sul voto) tutte le que-
stioni di sicurezza. In particolare, le password possono essere visibili
mentre vengono digitate.
"""
class MyMeta(type):
password: dict[type, str] = {}
@staticmethod
def richiedi_password() -> str:
password = input("Inserisci password: ")
if password != input("Conferma password: "):
raise Exception("Le due password non corrispondono.")
return password
def __new__(cls, name, parents, attrs):
print(f"{cls=} {name=} {parents=} {attrs=}")
created_class = super().__new__(cls, name, parents, attrs)
created_class._password = cls.richiedi_password()
class PwdProtected(metaclass=MyMeta, a=1, b=2, c=3):
def __init__(self) -> None:
if created_class._password != input(f"Inserisci password della classe {self.__class__.__name__}: "):
raise Exception("La password inserita non è valida.")
import string
vocali = set("aeiou")
consonanti = set('bcdfghjklmnpqrstvwxyz')
spazi = set(" \t\n")
def conta_vocali(stringa):
return len([char for char in stringa if char in vocali])
def conta_consonanti(stringa):
return len([char for char in stringa if char in consonanti])
def conta_spazi(stringa):
return len([char for char in stringa if char in spazi])
def conta_parole(stringa):
return len(stringa.split())
# Fai una classe che rappresenta un portafoglio: può vedere i contenuti convertiti in varie valute attraverso alcune sue proprietà
#
# Esempio:
# >>> w = Wallet(10.00) # Ho 10.00 euro
# >>> w.usd
# 11.47 # I miei 10 euro valgono 11.47 dollari
# >>> w.btc
# 0.000026 # I miei 10 euro valgono 0.000026 bitcoin
# >>> w.yen = 10000 # Ora nel mio portafoglio ci sono 10000 yen
# >>> w.eur # Quanti euro sono?
# 76.29 # 76.29
# Valute richieste: EUR USD BTC YEN
### Versione con property
class WalletProperty:
def __init__(self, eur):
try:
eur + 1
except TypeError:
raise Exception("numeri yo")
self.eur = float(eur)
@property
def usd(self):
return self.eur * 1.15
@usd.setter
def usd(self, dol):
self.eur = dol / 1.15
@usd.deleter
def usd(self):
self.eur = 0.0
@property
def btc(self):
return self.eur * 0.000026
@btc.setter
def btc(self, btc):
self.eur = btc / 0.000026
@btc.deleter
def btc(self):
self.eur = 0.0
@property
def yen(self):
return self.eur * 131.04
@yen.setter
def yen(self, yen):
self.eur = yen / 131.04
@yen.deleter
def yen(self):
self.eur = 0.0
w = WalletProperty(10.00)
assert w.usd == 11.50
w.usd = 10.00
assert w.eur == (10.00 / 1.15)
del w.usd
assert w.eur == 0.0
### Versione con gli accessori
class CurrencyConverter:
def __init__(self, conv):
self.conv = conv
def __get__(self, obj, objtype=None):
return obj.eur * self.conv
def __set__(self, obj, value):
obj.eur = value / self.conv
def __delete__(self, obj):
obj.eur = 0
class WalletAccessor:
def __init__(self, eur):
try:
eur + 1
except TypeError:
raise Exception("numeri yo")
self.eur = float(eur)
usd = CurrencyConverter(1.15)
yen = CurrencyConverter(131.04)
btc = CurrencyConverter(0.000026)
### Implementazione di property
class property:
def __init__(self, getter, setter, deleter):
self.getter = getter
self.setter = setter
self.deleter = deleter
def __get__(self, obj, objtype):
return self.getter()
def __set__(self, obj, value):
return self.setter(value)
def __delete__(self, obj):
return self.deleter()
@property
def boh():
...
boh = property(boh)
boh.setter = ...
boh.deleter = ...
def controllo_sbagliato(v):
if type(v) is not int:
raise Exception("Non è un int!?!?!")
# non funziona se le classi ereditano da int!
def controllo_giusto(v):
if not isinstance(v, int):
raise Exception("Non è un int!?!?!")
# now this is nice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment