Suppose I have a Python list of arbitrary length k
. Now, suppose I would like a random sample of n
, (where n <= k!) distinct permutations of that list. I was tempted to try:
import random
import itertools
k = 6
n = 10
mylist = list(range(0, k))
j = random.sample(list(itertools.permutations(mylist)), n)
for i in j:
print(i)
But, naturally, this code becomes unusably slow when k
gets too large. Given that the number of permutations that I may be looking for n
is going to be relatively small compared to the total number of permutations, computing all of the permutations is unnecessary. Yet it's important that none of the permutations in the final list are duplicates.
How would you achieve this more efficiently? Remember, mylist
could be a list of anything, I just used list(range(0, k))
for simplicity.
Aucun commentaire:
Enregistrer un commentaire