Python: fetching without replacing from a 2D mesh

I need a sample without replacement from all possible sets of numbers from range(n). That is, I have a set (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 these elements. I hope to avoid explicitly creating this collection.

I know that it random.sample(range(n), k)is simple and effective if I need a sample from a sequence of numbers, not tuples of numbers.

Of course, I can explicitly create a list containing all the possible ( n * n = n^2) tuples, and then call random.sample. But this is probably ineffective, if kmuch less n^2.

I'm not sure that in Python 2 and 3 everything works the same in terms of efficiency; I am using Python 3.

+5
source share
3 answers

Depending on how many of them you choose, it may be easier to just keep track of what things you have already selected (through set) and then iterate through until you get what you have "t already selected.

Another option is to simply use 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]
+6
source

You speak:

Of course, I can explicitly build a list containing everything possible (n * n = n ^ 2), and then call a random example. But this is probably inefficient if k is much less than n ^ 2.

, , ? , , , , .

, , , , , :

:

>>> import random
>>> all_sequences = [range(x) for x in range(10)]
>>> all_sequences
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]]
>>> random.sample(all_sequences, 3)
[[0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6, 7, 8]]

:

>>> import random
>>> selection = random.sample(range(10), 3)
>>> [range(x) for a in selection]
[[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]
0

Without attempt (without python):

random.shuffle(range(n))[:k]

Strike>

see comments. Did not sleep enough ...

-1
source

All Articles