Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: sampling without replacement from a 2D grid

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.

like image 728
max Avatar asked Jan 31 '11 06:01

max


People also ask

How do you do sampling without replacement in Python?

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.

How do you select multiple random values in a list Python?

Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.

How do you take a sample in Python?

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.


1 Answers

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]
like image 95
Amber Avatar answered Oct 06 '22 11:10

Amber