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

How to calculate combinations in Python

I want to calculate a combination set as a collection of all possible subsets of k items selected from n items. For example, if n = 4 and k = 3, then the items are the integers (0, 1, 2, 3), then there are 4 possible combination elements:

[0, 1, 2]
[0, 1, 3]
[0, 2, 3]
[1, 2, 3]

Is there a function to do it in Python?

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

>Solution :

itertools.combinations produces the desired output:

from itertools import combinations

n = 4
k = 3

# combinations() outputs tuples.
# Use list() to transform the tuples into lists.
print([list(combination) for combination in combinations(range(n), 3)])
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