I need a sample, without replacement, from among all possible tuples of numbers from range(n)
. That is, I have a collection of (0,0), (0,1), ..., (0,n), (1,0), (1,1), ..., (1,n), ..., (n,0), (n,1), (n,n), and I'm trying to get a sample of k of those elements. I am hoping to avoid explicitly building this collection.
I know random.sample(range(n), k)
is simple and efficient if I needed a sample from a sequence of numbers rather than tuples of numbers.
Of course, I can explicitly build the list containing all possible (n * n = n^2
) tuples, and then call random.sample
. But that probably is not efficient if k
is much smaller than n^2
.
I am not sure if things work the same in Python 2 and 3 in terms of efficiency; I use Python 3.
Random sample without replacement: random.sample() randomly samples multiple elements from a list without replacement. Pass a list to the first argument and the number of elements you want to get to the second argument. A list is returned. If the second argument is set to 1 , a list with one element is returned.
Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.
Python Random sample() MethodThe sample() method returns a list with a randomly selection of a specified number of items from a sequnce. Note: This method does not change the original sequence.
Depending on how many of these you're selecting, it might be simplest to just keep track of what things you've already picked (via a set
) and then re-pick until you get something that you haven't picked already.
The other option is to just use some simple math:
numbers_in_nxn = random.sample(range(n*n), k) # Use xrange in Python 2.x
tuples_in_nxn = [divmod(x,n) for x in numbers_in_nxn]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With