Calculating permutations without repetition in Python

I have two lists of items:

A = 'mno'
B = 'xyz'

I want to generate all permutations without replacement, simulating the replacement of all combinations of elements in B with elements in B without repeating. eg.

>>> do_my_permutation(A, B)
['mno', 'xno', 'mxo', 'mnx', 'xyo', 'mxy', 'xyz', 'zno', 'mzo', 'mnz', ...]

It is straightforward enough for me to write from scratch, but I know about the Python starndard itertools module , which I believe may already implement this. However, it is difficult for me to define a function that implements this exact behavior. Is there a function in this module that I can use for this?

+4
source share
3 answers

This is what you need:

["".join(elem) for elem in itertools.permutations(A+B, 3)]

permutations combinations, , (, , 'mxo' 'mox' ).

+7
+3

To have only unique, lexically sorted permutations, you can use this code:

import itertools

A = 'mno'
B = 'xyz'

s= {"".join(sorted(elem)) for elem in itertools.permutations(A+B, 3)}
0
source

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


All Articles