i have an array of 27 elements,and i don't want to generate all permutations of array (27!) i need 5000 randomly choosed permutations,any tip will be useful...
The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.
You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.
To generate one permutation use random.shuffle
and store a copy of the result. Repeat this operation in a loop and each time check for duplicates (there probably won't be any though). Once you have 5000 items in your result set, stop.
To address the point in the comment, Python's random module is based on the Mersenne Twister and has a period of 2**19937-1
, which is considerably larger than 27!
so it should be suitable for your use.
import random perm_list = [] for i in range(5000): temp = range(27) random.shuffle(temp) perm_list.append(temp) print(perm_list)
10888869450418352160768000000
I love big numbers! :)
AND
10888869450418352160768000001
is PRIME!!
EDIT:
#with duplicates check as suggested in the comment perm_list = set() while len(perm_list)<5000: temp = range(27) random.shuffle(temp) perm_list.add(tuple(temp)) # `tuple` because `list`s are not hashable. right Beni? print perm_list
WARNING: This wont ever stop if RNG is bad!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With