Python Random Module sample method with setstate notworking

I am wondering if I am doing it wrong when setting the random seed and state. The random number generated from the random.sample seems not predictable. Does anyone know why? Thanks.

>>> state = random.getstate()
>>> random.seed(7)           
>>> x = list(range(10))
>>> random.sample(x, 5)
[5, 2, 6, 9, 0]
>>> random.sample(x, 5)
[1, 8, 9, 2, 4]
>>> random.sample(x, 5)
[0, 8, 3, 9, 6]
>>> random.setstate(state)
>>> random.sample(x, 5)    
[3, 1, 9, 7, 8]
>>> random.sample(x, 5)
[4, 2, 7, 5, 0]
>>> random.sample(x, 5)
[9, 6, 7, 8, 0]

>Solution :

you have to change the seed before you get the state

In [1]: import random
   ...: random.seed(7)
   ...: state = random.getstate()
   ...: x = list(range(10))

In [2]: random.sample(x, 5)
   ...: 
Out[2]: [5, 2, 6, 9, 0]

In [3]: random.sample(x, 5)
Out[3]: [1, 8, 9, 2, 4]

In [4]: random.sample(x, 5)
Out[4]: [0, 8, 3, 9, 6]

In [5]: random.sample(x, 5)
Out[5]: [6, 9, 1, 7, 0]

In [6]: random.setstate(state)

In [7]: random.sample(x, 5)
Out[7]: [5, 2, 6, 9, 0]

In [8]: random.sample(x, 5)
Out[8]: [1, 8, 9, 2, 4]

In [9]: random.sample(x, 5)
Out[9]: [0, 8, 3, 9, 6]

In [10]: random.sample(x, 5)
Out[10]: [6, 9, 1, 7, 0]

Leave a Reply