Reputation: 85
I'm doing this:
random.randint(90, 110)
Pretty basic, returns values between 90 and 110 randomly.
However, I'm running the code 30 times, and I want these random values to change during the first 10 iterations, but I want the next 10 to change the same way as the previous 10 (i.e. random values in 11th/21st iteration are the same as the ones in 1st iteration, 12th/22nd = 2nd, etc.).
I tried to use random.seed(), so that the seed changes through iterations and tried to manipulate it so that the seed is the same for the 1st and the 11th/21st iterations. This does not seem to work though, as random.seed() seems to only work once.
Any way of doing this or does this not make sense?
EDIT: This is how I tried to do it using random.seed():
i = 0
while i < 30:
if i < 10:
sd = 100+i
elif (i >= 10) and (i < 20):
sd = 100+i-10
elif i >= 20:
sd = 100+i-20
random.seed(sd)
Upvotes: 2
Views: 136
Reputation: 36712
Your idea of using random seed is correct; you could implement it like this:
Every 10 iterations, the seed is reset, and the sequence of pseudo-random numbers restarts from the beginning.
import random
SEED = 1234
for idx in range(30):
if idx % 10 == 0:
random.seed(SEED)
print()
print(random.randrange(90, 110), end= ' ')
94 103 99 106 106 95 95 106 110 108
94 103 99 106 106 95 95 106 110 108
94 103 99 106 106 95 95 106 110 108
Upvotes: 3
Reputation: 26037
Without random.seed
, you could do it using a list-comprehension and join
.
Find first 10 randoms and then duplicate them to equal 30 count.
import random
randoms = []
for _ in range(10):
randoms.append(random.randint(90, 110))
print('\n'.join([' '.join(map(str, randoms)) for _ in range(3)]))
# 110 108 93 104 98 101 95 99 104 94
# 110 108 93 104 98 101 95 99 104 94
# 110 108 93 104 98 101 95 99 104 94
Upvotes: 0
Reputation: 109
Here's a code that works. I used array to store first 10 random entries and used i%10 to get appropriate value everytime
import random
random_arr=[] # 10 random numbers will be stored here
for i in range(10):
random_arr.append(random.randint(10,90))
i = 0
while(i < 30):
random_value = random_arr[i%10]
print(random_value,end=" ")
i+=1
OUTPUT:
32 27 28 86 11 54 26 24 38 16 32 27 28 86 11 54 26 24 38 16 32 27 28 86 11 54 26 24 38 16
Upvotes: 0
Reputation: 16966
First generate the 30 seeds with the kind of repetition you want and then set the seeds before you generate the random number.
import random
seeds = np.arange(10)
seeds = np.hstack((seeds,seeds,seeds))
for i in range(30):
random.seed(seeds[i])
if i%10 ==0:
print()
print(random.randint(90, 110),end=' ')
output:
102 94 91 97 97 109 108 100 97 104
102 94 91 97 97 109 108 100 97 104
102 94 91 97 97 109 108 100 97 104
Upvotes: 0