0

so when I generate 1000 sets of random numbers (0..2000) in Python, I can easily do something like this:

iters = 1000
randIdx = []
numbers = range(0, 2000)
for i in range(iters):
        randIdx.append(random.sample(numbers, 8))

The problem is that the code is VERY slow. Is there a way to avoid the for loop to tell the function to just put out 1000 sets or is there some kind of workaround? I thought of just generating 8000 random numbers but the problem occurs that it is not possible to do that when in a set of 8 numbers duplicates aren't allowed!

Example:

 randIdx=[]
 indexRange = range(0, 3)  
 for i in range(5):
     randIdx.append(random.sample(indexRange, 2))

[[0, 1], [2, 1], [2, 0], [1, 0], [2, 1]]
jpp
  • 159,742
  • 34
  • 281
  • 339
Miau
  • 301
  • 1
  • 3
  • 12

1 Answers1

2

You can use the numpy library for this:

import numpy as np

arr = np.random.randint(0, 2000, (1000, 8))

# array([[1026,   46, 1620, ...,  534, 1098, 1406],
#        [1081, 1235,  484, ..., 1124,  841,    4],
#        [1189, 1505, 1943, ...,   55, 1547, 1936],
#        ..., 
#        [1242,  877, 1129, ...,  230, 1226, 1399],
#        [1134,  939,  969, ..., 1600,  288, 1479],
#        [ 492,    5,  545, ..., 1093, 1805, 1404]])

Then just slice the array for one selection, e.g. arr[0] will give you the first row as an array.

jpp
  • 159,742
  • 34
  • 281
  • 339