Cerin
Cerin

Reputation: 64739

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?

Upvotes: 4

Views: 2514

Answers (4)

Alexey Kiselev
Alexey Kiselev

Reputation: 11

This code will be usefull if you want to count permutations without repetitions:

from collections import Counter
from math import factorial
s=input()
c=Counter(s)
p=factorial(len(s))
for v in c.values():
    p//=factorial(v)
print(p)

All possible permutations count with repetitions is equal to factorial of string length. But if there are repeated symbols in a string, then we must exclude permutations of that sybols between each other. Count of that permutations is equal to factorial of the symbol occurences count. Counter was used for that purpose in the above code.

Upvotes: 1

Ukimiku
Ukimiku

Reputation: 618

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)}

Upvotes: 1

ely
ely

Reputation: 77424

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).

Upvotes: 8

msvalkon
msvalkon

Reputation: 12077

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.

Upvotes: 4

Related Questions