Reputation: 1722
I would like to generate a random number 193 times, but set a seed so I can get the same number later on for each instance. Because, I could not find a function to set a seed X times, I wrote the following code:
rand_list_raw = []
val_length = int(len(all_articles)*0.15)
seeds = list(range(0,val_length))
index = 0
while len(rand_list_raw) < val_length:
seed = seeds[index]
random.seed(seed)
rand_num = random.randrange(0, 1290, 1)
rand_list_raw.append(rand_num)
index += 1
Checking the length of the unique variables in rand_list_raw
, I concluded that random.seed()
has a many-to-one mapping, so that multiple instances of a random seed with a different numbers, may results in the same outcome. It actually makes sense, since the range of input variables in infinite and the range of output variables is finite.
len(set(rand_list_raw))
Is there a way to guarantee different numbers (other than hard coding it)?
Ps. I know that I could also just create a list with unique random numbers within the range and export it. But that's not the point.
Upvotes: 0
Views: 533
Reputation: 1145
Why seed it n times? You could just step through from a starting seed and always have the same order. Consider:
rand_dict = {}
rand_list = []
val_length = int(len(all_articles)*0.15)
seed = 1 #whatever you want
step = 0
random.seed(seed)
while len(rand_list_raw) < val_length:
step+=1
rand_num = random.randrange(0, 1290, 1)
try:
test = rand_dict[rand_num] #check if key exists if it does we dont do anything
except KeyError:
rand_list.append(rand_num)
rand_dict[rand_num] = step
Then if you want to get the same numbers again. Simply seed again with the same seed and iterate through using a generator for the same number of steps that is stored in the dict.
Example to get your number back. Using seed = 1, at step = 5 value is 241.
random.seed(seed)
step = rand_dict[241]
i = 0
while(i<step)
buf = random.randrange(0,1290,1)
i+=1
print(buf)
>> 241
Upvotes: 1