objectif
Tirer k éléments avec replacement selon des poids.
code minimal
import random
pop = ["a","b","c"]
w = [0.0, 0.0, 1.0]
draw = random.choices(population=pop, weights=w, k=3)
print(all(x == "c" for x in draw)) # attendu: True (poids forcé)
utilisation
import random
pop = ["x","y"]
draw = random.choices(pop, weights=[1,3], k=4)
print(len(draw) == 4)
variante(s) utile(s)
import random
print(isinstance(random.choices([1], k=2), list))
notes
- Pour sans replacement, utilisez random.sample(k=n).
- Les poids peuvent être relatifs; normalisation automatique.