fcamuso

Corso Python - lezione 22 (by sharing, default, lambda)

Jun 19th, 2026
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.29 KB | None | 0 0
  1. def f1(n: int):
  2.     n *=2
  3.     # print(n)
  4.     return n
  5.  
  6.  
  7.  
  8. # una funzione riceve sempre l'indirizzo dell'oggetto esterno
  9. # passaggio by sharing (by object reference)
  10.  
  11. # quando si passa un immutable la funzione non potrà
  12. # modificarlo
  13. numero = 34
  14. f1(numero) # numero vale ancora 34
  15.  
  16. # questo è il modo idiomatico per la modifica
  17. numero = f1(numero)  # ora numero vale 68
  18. # print(numero)
  19.  
  20. # passando um mutable la funzione riceve
  21. # anche in questo caso l'indirizzo dell'oggetto
  22. # esterno ma potrà modificarne il CONTENUTO
  23.  
  24. def f2(l: list[str]):
  25.     l.append("hello")
  26.     l = []
  27.     return l
  28.  
  29. elenco: list[str] = ["Salve", "Buenas dias"]
  30. f2(elenco)
  31. # print(elenco)
  32.  
  33. # i parametri con valore di default vanno messi tutti per ultimi
  34. def disegna(figura: str, colore_tratto:str = 'black',
  35.             colore_sfondo: str|None = None):
  36.  
  37.     print("Tratto: " + colore_tratto)
  38.     print("Sfondo: " + (colore_sfondo if colore_sfondo is not None else "None"))
  39.     return
  40.  
  41. disegna(figura="q")
  42. print("-"*20)
  43.  
  44. disegna(figura="q", colore_sfondo="giallo")
  45. print("-"*20)
  46.  
  47. disegna(figura="q", colore_tratto="giallo")
  48. print("-"*20)
  49.  
  50. def f3(a=0, b=1, c=2, d=3, e=4):
  51.     print (f"a={a} b={b} c={c} d={d} e={e}")
  52.  
  53. f3(12, 23)
  54.  
  55. # def funzione_di_calcolo_key(ele: dict[str, str|int]):
  56. #     return ele["eta"]
  57.  
  58. # lambda function
  59. utenti = [
  60.     {"nome": "Alice", "eta": 30},
  61.     {"nome": "Bob", "eta": 25},
  62.     {"nome": "Charlie", "eta": 35}
  63. ]
  64.  
  65. # Ordina la lista in base al valore della chiave "età"
  66. utenti_ordinati = sorted(utenti, key= lambda ele: ele["eta"] )
  67. print(utenti_ordinati)
  68.  
  69. utenti = [
  70.     {"id": 1, "nome": "Mario", "cognome": "Rossi", "username": "mrossi"},
  71.     {"id": 2, "nome": "Luigi", "cognome": "Verdi", "username": "lverdi"}
  72.     # ecc...
  73. ]
  74.  
  75.  
  76. def ottieni_estrattore(formato_richiesto):
  77.  
  78.     match formato_richiesto:
  79.         case  "nome_completo":
  80.             return lambda utente: f"{utente['nome']} {utente['cognome']}"
  81.  
  82.         case "id_formattato":
  83.             return lambda utente: f"USER-{utente['id']:05d}"
  84.  
  85.         case _:
  86.             return lambda utente: utente.get('username', 'Anonimo')
  87.  
  88. def ottieni_estrattore2(formato_richiesto):
  89.  
  90.     match formato_richiesto:
  91.         case "nome_completo":
  92.             def estrai_nome(utente):
  93.                 return f"{utente['nome']} {utente['cognome']}"
  94.             return estrai_nome
  95.  
  96.         case "id_formattato":
  97.             def estrai_id(utente):
  98.                 return f"USER-{utente['id']:05d}"
  99.             return estrai_id
  100.  
  101.         case _:
  102.             def estrai_default(utente):
  103.                 return utente.get('username', 'Anonimo')
  104.             return estrai_default
  105.  
  106.  
  107. estrattore = ottieni_estrattore("id_formattato")
  108.  
  109. for utente in utenti:
  110.     print(estrattore(utente))
  111.  
  112.  
  113. # dati_grezzi = ["   mela  ", "kiwi", "   BanAna   ", "te"]
  114. #
  115. # lambda1 = lambda s: s.strip().lower() if len(s.strip().lower()) > 4 else "TROPPO CORTA"
  116. # # Output: ['TROPPO CORTA', 'TROPPO CORTA', 'banana', 'TROPPO CORTA']
  117. #
  118. # lambda1_ottimizzata = lambda s: pulita if len(pulita := s.strip().lower()) > 4 else "TROPPO CORTA"
  119. #
  120. # f = lambda x: [i for i in range(x)]
  121. # print(f(5))
  122.  
  123. # lambda1 = lambda x: (y := x + 1) * 2
  124. # print(y)
  125. #
  126. # lambda2 = lambda x: x if x > 0 else 0
  127. # lambda3 = lambda x: [i for i in range(x)]
  128.  
  129.  
Advertisement
Add Comment
Please, Sign In to add comment