Skip to content Skip to sidebar Skip to footer

Set Has No Order But Random.choice( List(set) ) Is Unstable Given Random Seed

I found a weird result of this below code on my project (below code is equivalent to the code in my project since I have to remove parts that are irrelevant to the question): impor

Solution 1:

A set is unordered and so will yield its elements in any order. However, this order is consistent within one python invocation. That is, set_ = set(range(N)); list(set_) == list(set_) is always true within in the same python program. Python 3.2+ explicitly makes sure that the ordering will inconsistent from one python instance to the next (this is a security consideration relating to denial of service attacks involving dictionary construction). This is the behaviour you are seeing.

To avoid this you need to set the environment variable PYTHONHASHSEED to the same value before you start your program. This is in addition to setting the random seed before using random.choice.

export PYTHONHASHSEED=1
python myscript.py

A simpler solution, however, is to create a sorted list before doing random.choice. ie.

random.choice(sorted({1, 2, 3}))

Post a Comment for "Set Has No Order But Random.choice( List(set) ) Is Unstable Given Random Seed"