Permutations without repetition of output in Python

I want to get all possible permutations of two different elements grouped in four, without repeating the output, but repeating elements (obviously, you need to repeat the elements to create combinations of 4 with only two elements).

So, some things I tried:

sorted(list(map(lambda x: "".join(x), list(permutations('AB', 4))))) 

returns an empty list. So I tried this:

 sorted(list(map(lambda x: "".join(x), list(permutations('AABB', 4))))) 

And it is closed to the output that I expect, but filled with redundant elements, just a few of them:

 ['AABB','AABB','AABB','AABB','ABAB','ABAB','ABAB',... 

What I was expecting to get is actually:

 ['AABB','ABAB','ABBA','BAAB','BABA','BBAA'] 

I also tried functions () and product () instead of permutations () without success, but maybe my arguments did not match this problem.

Any ideas?

Thank you very much!

PS. As Antoine pointed out, there is a workaround that uses a set instead of a list, for example:

 sorted(list(map(lambda x: "".join(x), set(permutations('AABB', 4))))) 

This gives the expected result, but it still generates all the repetitions, but it can just be filtered because the sets cannot have a repeating element, so this is probably not the most efficient way to do this.

+5
source share
2 answers

Well, you can use set instead of a list and get the desired result.

 sorted(set(map(lambda x: "".join(x), list(permutations('AABB', 4))))) 

But be warned that this may not work very well for a very large number of items in a bag. It does not scale

gives

 ['AABB', 'ABAB', 'ABBA', 'BAAB', 'BABA', 'BBAA'] 

A little more performance maybe

 sorted(map(lambda x: "".join(x), set(permutations('AABB', 4)))) 

The following is a list of equivalent permutation pythons: https://docs.python.org/2/library/itertools.html#itertools.permutations

The source code is implemented in C, so it will work faster. After all, permutations of large numbers of elements simply don't scale regardless of whether you leave duplicates.

+6
source

Just copy and paste this answer that I don’t see how it can be improved, so you should enhance that

 def permute_unique(myList): perms = [[]] for i in myList: new_perm = [] for perm in perms: for j in range(len(perm) + 1): new_perm.append(perm[:j] + [i] + perm[j:]) # handle duplication if j < len(perm) and perm[j] == i: break perms = new_perm return perms 

Result:

 >>> sorted(list(map(lambda x: "".join(x), permute_unique('AABB') ))) ['AABB', 'ABAB', 'ABBA', 'BAAB', 'BABA', 'BBAA'] 
0
source

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


All Articles