Unique combinations from a set with duplicates

In python, when I write:

L = [2,2,3]
list(itertools.combinations(L, 2))

I get this:

[(2, 2), (2, 3), (2, 3)]

I want to get only this:

[(2, 2), (2, 3)]

That is, each combination should appear only once, even though the original list contains two 2’s.

What is an efficient way to get each subset of L (of size 2) only once?

What I tried:

list(itertools.combinations(set(L), 2))

returns only:

[(2, 3)]

This is not good – I want to get the (2,2) too, since it is a subset of L.

list(itertools.combinations_with_replacement(set(L), 2))

returns:

[(2, 2), (2, 3), (3, 3)]

This is not good – I do not need the (3,3), since it is not a subset of L.

>Solution :

from more_itertools import distinct_combinations

print(*distinct_combinations([2, 2, 3], 2))

Output:

(2, 2) (2, 3)

Documentation, which says:

Equivalent to set(combinations(iterable)), except duplicates are not generated and thrown away. For larger input sequences this is much more efficient.

Leave a Reply