← retour aux snippets

random: échantillonnage reproductible

Utiliser un générateur local pour isoler l'aléatoire et reproduire.

objectif

Utiliser un générateur local pour isoler l’aléatoire et reproduire.

code minimal

import random
rng = random.Random(0)  # graine locale
sample = rng.sample(range(10), 3)
print(len(sample) == 3 and sample != rng.sample(range(10), 3))  # attendu: True

utilisation

import random
rng = random.Random(42)
print(rng.randint(1, 3) in (1,2,3))

variante(s) utile(s)

import random
rng = random.Random(0)
a = [rng.random() for _ in range(2)]
b = [random.random() for _ in range(2)]
print(a != b)  # générateurs indépendants

notes

  • Préférez un Random dédié plutôt que random global partagé.
  • Pour sécurité, utilisez secrets (pas random).