How to find all possible sequences of elements in a list?

I have a list [2,3,4]. How to find all possible sequence of elements in a list? Thus, the output should be: [2,3,4] [2,4,3] [3,2,4] [3,4,2] [4,2,3] [4,3,2]

+6
source share
4 answers

You can do this easily using itertools.permutations() :

 >>> from itertools import permutations >>> list(permutations([2, 3, 4])) [(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)] 

And if for some reason you need lists instead of tuples:

 >>> map(list, permutations([2, 3, 4])) [[2, 3, 4], [2, 4, 3], [3, 2, 4], [3, 4, 2], [4, 2, 3], [4, 3, 2]] 
+21
source

You are looking for permutations, something like this should work:

 import itertools itertools.permutations([2,3,4]) 
+5
source

the beginning of a large lottery, except that the data will be generated as such

 ist(permutations([2, 3, 4],[7,2,5],[8,1,4,9])) 

the problem is that the first group is used to create numbers only in the first column of the second - for 2 columns, and the third - for the 3rd

the output will be three numbers, so the permutation is different

+2
source

Just to let you know:

 def unique_perms(elems): """returns non-duplicate permutations if duplicate elements exist in `elems` """ from itertools import permutations return list(set(permutations(elems))) 

But if you do something like this:

 print len(unique_perms(elems)) 

Then try the following:

 def fac(n): """n!""" if n == 1: return n return n * fac(n -1) def unique_perm_count(elems) n = len(elems) return fac(2 * n) / fac(n) ** 2 
+1
source

Source: https://habr.com/ru/post/907076/


All Articles