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.
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: