Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading