:PROPERTIES:
:ID:       cc0e3fd0-2832-4bf6-909f-354507f7ed11
:mtime:    20220528110155
:ctime:    20220528104202
:END:
#+title: Set et frozenset

* /Set/
Un /set/ est un ensemble /mutable/ et non ordonné d'éléments uniques.
#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
print(f'{groceries = }')
#+END_SRC

#+RESULTS:
: groceries = {'milk', 'chocolate', 'cheese'}

** Egalité
L'ordre n'a pas d'impact sur l'égalité entre deux /set/ :
#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
print(f'{set(["milk", "cheese", "chocolate"])==set(["chocolate", "milk", "cheese"]) = }')
#+END_SRC

#+RESULTS:
: set(["milk", "cheese", "chocolate"])==set(["chocolate", "milk", "cheese"]) = True

** /Set comprehension/
#+BEGIN_SRC python :results output
veggies = ["broccoli", "carrot", "tomato", "pepper", "lettuce"]
veggies_with_c = {veggie for veggie in veggies if "c" in veggie}

print(f'{veggies = }')
print(f'{veggies_with_c = }')
#+END_SRC

#+RESULTS:
: veggies = ['broccoli', 'carrot', 'tomato', 'pepper', 'lettuce']
: veggies_with_c = {'carrot', 'lettuce', 'broccoli'}

** Opérations sur les /set/
*** L'intersection entre des /set/ est réalisée avec l'opérateur ~&~
#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
treats = {"chocolate", "popcorn", "cookie"}

print(f'{groceries & treats = }')
#+END_SRC

#+RESULTS:
: groceries & treats = {'chocolate'}

*** L'union entre des /set/ est réalisée avec l'opérateur ~|~
#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
treats = {"chocolate", "popcorn", "cookie"}

print(f'{groceries | treats = }')
#+END_SRC

#+results:
: groceries | treats = {'cheese', 'popcorn', 'chocolate', 'milk', 'cookie'}

*** La différences entre /set/ est réalisée avec l'opérateur ~-~
#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
treats = {"chocolate", "popcorn", "cookie"}

print(f'{groceries - treats = }')
#+END_SRC

#+RESULTS:
: groceries - treats = {'milk', 'cheese'}

* /Frozenset/
A l'inverse du /set/, le /frozenset/ est /immutable/ et est donc /hashable/ (utilisable comme clé des /dict/).

#+BEGIN_SRC python :results output
groceries = {"milk", "cheese", "chocolate"}
frozen_groceries = frozenset(groceries)

try:
    frozen_groceries.add("beans")
except AttributeError as e:
    print(e)

d = {}

try:
    d[groceries] = None
except TypeError as e:
    print(e)

d[frozen_groceries] = None
print(f'{d = }')
#+END_SRC

#+RESULTS:
: 'frozenset' object has no attribute 'add'
: unhashable type: 'set'
: d = {frozenset({'chocolate', 'milk', 'cheese'}): None}



* Références
 * [[https://mathspp.com/blog/pydonts/set-and-frozenset][Set and frozenset - Pydon't]]
