Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate permutations of array in python?

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...

like image 925
user257522 Avatar asked Jan 23 '10 19:01

user257522


People also ask

How do you find the permutation of an array in Python?

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}.

How do you generate permutations of an array?

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.


2 Answers

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.

like image 120
Mark Byers Avatar answered Sep 28 '22 09:09

Mark Byers


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!

like image 35
Pratik Deoghare Avatar answered Sep 28 '22 10:09

Pratik Deoghare