Home > database >  How to make random choose from a set in Python reproducible
How to make random choose from a set in Python reproducible

Time:12-28

I wrote a simple sample code here. In fact, elements will be added or deleted from the set and a random element will be chosen from the set on each iteration in my program.

But even if I run the simplified code below, I got different output every time I run the codes. So, how to make the outputs reproducible?

import random
random.seed(0)
x = set()
for i in range(40):
    x.add('a' str(i))
print(random.sample(x, 1))

CodePudding user response:

The problem is that a set's elements are unordered, and will vary between runs even if the random sample chooses the same thing. Using random.sample on a set is in fact deprecated since python 3.9, and in the future you will need to input a sequence instead.

You could do this by converting the set to a sequence in a consistently ordered way, such as

x = sorted(x)

or probably better, just use a type like list in the first place (always producing ['a24'] in your example).

x = ['a'   str(i) for i in range(40)]
  • Related