vendredi 17 juillet 2020

What's the best way to generate unique permutations in Python?

I have 2 choices between 0 and 1 for each item where I will have N elements sequenced one after another generating a unique combination.

So something like these (sequence length=10):

0, 1, 0, 1, 0, 1, 0, 1, 0, 1
0, 0, 0, 1, 0, 1, 0, 1, 0, 1
0, 1, 1, 1, 0, 1, 0, 1, 0, 1
1, 1, 1, 1, 0, 1, 0, 1, 0, 1

As you see these are all unique permutations. I will have 10000 of these permutations (for example). But the key info is I don't need all the permutations, but rather only save a limited set of them, and ideally out of order, so it's a bit more "random".

My current solution is to generate random numbers between 0 and 1, and append them in an array up to N elements. Then turn this array into a string and if this string is not already added to my list above, then add this, otherwise repeat the same step to generate a different permutation.

So that means using a while loop.

Is there a smarter, or more elegant way to do this?




Aucun commentaire:

Enregistrer un commentaire