Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate permutations of length LEN given a list of N Items?

Tags:

Note: I'm working in python on this.

For example, given a list:

list = ['a','b','c','d','e','f','g','h','i','j'] 

I want to generate a list of lists with all possible 3-item combinations:

['a','b','c'], ['a','b','d'], ['a','b','e'] 

The permutations should not use the same item twice in a permutation, but the order is important and represents distinct permutations that should be included, e.g.,

['a','b','c'], ['a','c','b'] 

Should both be included.

"3" is the magic length for the permutations I'm looking to generate, but I wouldn't look down on a solution for arbitrary length permutations.

Thanks for any help!

like image 516
Odj fourth Avatar asked Feb 18 '12 02:02

Odj fourth


People also ask

How do you generate all permutations 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 find the length of a permutation in Python?

length() : length() is a sympy Python library function that finds the number of integers moved by the permutation.

How do you generate all 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

itertools.permutations(my_list, 3) 
like image 192
Ned Batchelder Avatar answered Oct 09 '22 10:10

Ned Batchelder


Assuming you're in python 2.6 or newer:

from itertools import permutations for i in permutations(your_list, 3):     print i 
like image 30
michaelfilms Avatar answered Oct 09 '22 08:10

michaelfilms