Reputation: 325
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.
Upvotes: 0
Views: 273
Reputation: 2516
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
.
The above answer works if the input has all unique elements. If there are repeated elements then take the product of (count + 1) of every element, and again subtract one at the end to remove the empty set.
E.g. [1,1,1,2,2,3]: our counts are 3, 2, 1, so our answer is 4 * 3 * 2 - 1 = 23.
The idea is that for each element, you can have anywhere from 0 up to count(element) in your sublists.
Upvotes: 3