Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating permutations without repetitions in Python

I have two lists of items:

A = 'mno'
B = 'xyz'

I want to generate all permutations, without replacement, simulating replacing all combinations of items in A with items in B, without repetition. e.g.

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

This is straight-forward enough for me to write from scratch, but I'm aware of Python's starndard itertools module, which I believe may already implement this. However, I'm having trouble identifying the function that implements this exact behavior. Is there a function in this module I can use to accomplish this?

like image 559
Cerin Avatar asked Dec 25 '22 12:12

Cerin


2 Answers

Is this what you need:

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

and replace permutations with combinations if you want all orderings of the same three letters to be collapsed down into a single item (e.g. so that 'mxo' and 'mox' do not each individually appear in the output).

like image 155
ely Avatar answered Jan 04 '23 23:01

ely


You're looking for itertools.permutations.

From the docs:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

like image 34
msvalkon Avatar answered Jan 04 '23 23:01

msvalkon