Reputation: 1007
Outputting a set of numbers does not give the same sequence even after using random.seed(myseed)
. This only occurs in Python3, not in Python2 (both on a Debian stable system). Is it a bug or something wrong with my code ?
import random
seed=20.0
random.seed(seed)
print("seed: {}".format(seed))
test = [str(random.randint(0,1000)) for _ in range(10)]
print(', '.join(test))
ss = set(test)
print(', '.join(ss))
Below Python3 gives a different sequences at each run, but Python2 gives similar sequences across all runs(as expected).
$ python3 --version
Python 3.4.2
$ python2 --version
Python 2.7.9
#same sequences
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
#diff sequences
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
926, 690, 784, 702, 740, 927, 266, 154, 901, 805
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
702, 926, 784, 901, 154, 266, 805, 690, 740, 927
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
805, 926, 901, 784, 740, 927, 154, 690, 266, 702
Upvotes: 0
Views: 325
Reputation: 44131
You are actually incorrect. Python 3 is returning the same set of numbers. You are making an assumption that set
an unordered container will have the same order each time you execute python which is incorrect.
For example, for the last two python3 tests:
>>> a = set([702, 926, 784, 901, 154, 266, 805, 690, 740, 927])
>>> b = set([805, 926, 901, 784, 740, 927, 154, 690, 266, 702])
>>> a == b
True
You can ensure that your sets
are correctly ordered by using sorted
print(', '.join(sorted(test)))
Upvotes: 5