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...
itertools.permutations
. It's a generator, so it won't create the whole list of permutations. You could skip randomly until you've got 5000.
You may want the itertools.permutations() function. Gotta love that itertools module!
NOTE: New in 2.6
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!
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.
# apermindex should be a number between 0 and factorial(len(alist))
def perm_given_index(alist, apermindex):
for i in range(len(alist)-1):
apermindex, j = divmod(apermindex, len(alist)-i)
alist[i], alist[i+j] = alist[i+j], alist[i]
return alist
call like perm_given_index(['a','b','c'], 3)
i think this uses the Lehmer code for the permutation as the values of j match that