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

Python print every unique combination of list items

What is the cleanest (most "pythonic") way of printing every unique combination of three items in the following list?

strats = ["1","2","3","4"]

The solution needs to avoid duplicates:

1 and 1 and 1 No (not unique)
1 and 1 and 2 No (not unique)
1 and 1 and 3 No (not unique)
...
1 and 2 and 3 Yes
1 and 2 and 4 Yes
1 and 3 and 1 No (not unique)
1 and 3 and 2 No (occurred previously)
...

I am using numbers here just for clarity, the actual project involve text strings and there are 24 of them, but the same logic should apply.

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

Here is my first attempt:

strats = ["1","2","3","4"]

for a in strats:
    for b in strats:
        for c in strats:
            if a != b and a != c and b!=c:
                print(a+" and "+b+" and "+c)

The problem with the output is that it contains duplicates:

1 and 2 and 3 Fine
1 and 2 and 4 Fine
1 and 3 and 2 Duplicate
1 and 3 and 4 Fine
1 and 4 and 2 Duplicate
1 and 4 and 3 Duplicate
...

>Solution :

Python has built-in support for permutations and combinations. This will print out all the unique sets of 3 from a universe of N items:

import itertools
for nxt in itertools.combinations(strats, 3):
   print(nxt)

There are 2,024 ways of taking 3 items from a population of 24.

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