Python random.setstate()
Python random.setstate()
The random module is used to generate random numbers in Python. These numbers are not actually random, but rather pseudo-random. This means that these randomly generated numbers can be determined.
random.setstate()
The setstate() method of the random module is used in conjunction with the getstate() method. After obtaining the state of the random number generator using the getstate() method, the setstate() method is used to restore the random number generator to a specified state.
The setstate() method requires a state object as an argument, which can be obtained by calling the getstate() method.
Example 1:
# import the random module
import random
# capture the current state
# using the getstate() method
state = random.getstate()
# print a random number of the
# captured state
num = random.random()
print("A random number of the captured state: "+ str(num))
# print another random number
num = random.random()
print("Another random number: "+ str(num))
# restore the captured state
# using the setstate() method
# pass the captured state as the parameter
random.setstate(state)
# now printing the same random number
# as in the captured state
num = random.random()
print("The random number of the previously captured state: "+ str(num))
Output:
A random number of the captured state: 0.8059083574308233
Another random number: 0.46568313950438245
The random number of the previously captured state: 0.8059083574308233
Example 2:
# import the random module
import random
list1 = [1, 2, 3, 4, 5]
# capture the current state
# using the getstate() method
state = random.getstate()
# Prints list of random items of given length
print(random.sample(list1, 3))
# restore the captured state
# using the setstate() method
# pass the captured state as the parameter
random.setstate(state)
# now printing the same list of random
# items
print(random.sample(list1, 3))
Output:
[5, 2, 4]
[5, 2, 4]