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]]
2
  • Your current code raises an exception, can you show an example of the desired output for smaller inputs? e.g. range(5) and numbers = 3 Commented Feb 19, 2018 at 9:38
  • sorry, just changed the range from iters to numbers.. Commented Feb 19, 2018 at 9:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.