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 or math: How to count all possible combinations of a list's elements?

Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or ‘sub-lists’), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345.

I know how to get nCr, the count of combinations of r elements of a list with total n elements.
Python 3.8 or above:

from math import comb
p, r = 5, 2
print(comb(p, r))

Then I could do nC1 + nC2 +...+ nCn. But is there a better/faster way?

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

p, result = 5, 0
for r in range(1, 6):
    result += comb(p, r)
print(result)

Would appreciate your answers.

>Solution :

This specific sum is equal to 2^n -1 🙂

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