Lets say L=[1,2,3,4,5]
How can I create 4 (or maximum of len(L)
!) unique random orders of L?
Expected result should look like this:
[[2,1,3,4,5],[5,3,2,1,4],[4,3,2,1,5],[5,1,3,2,4]
Lets say L=[1,2,3,4,5]
How can I create 4 (or maximum of len(L)
!) unique random orders of L?
Expected result should look like this:
[[2,1,3,4,5],[5,3,2,1,4],[4,3,2,1,5],[5,1,3,2,4]
As pointed out in this post, you can use itertools
to generate all possible permutations of the list:
all_perms = list(itertools.permutations(L))
then if you only want 4 random choices (without replacement) of all possible permutations, you can do something like:
random.sample(all_perms, k=4)
Fairly standard approach: pick random samples and throw away duplicates for a small sample, or partial shuffle if you're generating a sample that covers most of the sample space.
import itertools
import math
import random
def n_random_permutations(n, l):
if n * 3 < math.factorial(len(l)):
# rejection sampling
# generate samples and throw them away if we already picked them.
samples = set()
while len(samples) < n:
sample = list(l)
random.shuffle(sample)
samples.add(tuple(sample))
samples = list(samples)
random.shuffle(samples)
return samples
else:
# generate every possible permutation and pick n of them.
permutations = list(itertools.permutations(l))
return random.sample(permutations, n)