Python: a given set of N elements, select k randomly, m times

Given a set of N elements, I want to choose m random, non-repeating subsets of k elements.

If I were looking to generate everything , then N would choose k combinations, I could use itertools.combination , so one way to do what I ask is:

import numpy as np
import itertools
n=10
A = np.arange(n)
k=4
m=5
result = np.random.permutation([x for x in itertools.permutations(A,k)])[:m]
print(result)

The problem, of course, is that this code first generates all possible permutations, and this can be quite expensive.

Another suboptimal solution would be to choose randomly each time one swap ( for example, select from random-from-combinations , then sort to get the swap), and discard it if it is already selected.

Is there a better way to do this?

+4
source share
2 answers

The easiest way to do this: random.shuffle(range)then take the first k elements (you need to repeat until valid samples are collected).

Of course, this procedure cannot guarantee unique designs. You should check the new pattern for your historical hash if you really need it.

Since Pyton2.3 random.sample(range, k)can be used to create a sample in a more efficient way

+1

. , k n, m "", .

, , . m = 50, n = 10 k = 4, 60 . , .

random.sample k , . , set .

import random

n = 10
A = list(range(n))
k = 4
m = 5

samples = set()
tries = 0
while len(samples) < m:
    samples.add(tuple(sorted(random.sample(A, k))))
    tries += 1

print(samples)
print(tries)

# {(1, 4, 5, 9), (0, 3, 6, 8), (0, 4, 7, 8), (3, 5, 7, 9), (1, 2, 3, 4)}
# 6
# 6 tries this time !
+1

Source: https://habr.com/ru/post/1693070/


All Articles