how to generate permutations of array in python? how to generate permutations of array in python? python python

how to generate permutations of array in python?


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 randomperm_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 commentperm_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!


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.