Python or math: How to count all possible combinations of a list's elements?

Question:

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?

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

Would appreciate your answers.

Asked By: Nov05

||

Answers:

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

Answered By: C4stor

This concept is called a power set in mathematics, and it refers to all subsets of a given set. Your question refers to the size of the power set which is 2^n where n is the size of your original set. This total includes the empty set, so as C4stor said, your total would be 2^n - 1.

Answered By: jprebys
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.