How To Calculate The Number Of All Possible Combinations For A Range Of Numbers From 1 To N?
Other than doing this: from itertools import combinations def brute_force(x): for l in range (1,len(x)+1): for f in list(combinations(range(0,len(x)),l)): y
Solution 1:
Always there is 2−1 non-empty subset of set {1,...,n}
.
For example consider the list ['a','b','c']
:
>>> [list(combinations(['a','b','c'],i)) for i inrange(1,4)]
[[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'), ('b', 'c')], [('a', 'b', 'c')]]
>>> l=[list(combinations(['a','b','c'],i)) for i inrange(1,4)]
>>> sum(map(len,l))
7
That the length of our list is 3 so we have 2-1=7 combinations.
And for a range(10)
:
>>>l=[list(combinations(range(10),i)) for i inrange(1,11)]>>>sum(map(len,l))
1023 #2^10-1 = 1024-1=1023
Note if you want to count the empty subset you can just use 2^n
.
Actually at a mathematical perspective :
a k-combination of a set is a subset of k distinct elements of S. If the set has n elements, the number of k-combinations is equal to the binomial coefficient :
and for all combinations :
Solution 2:
Assuming you have a list from [1, 10)
, and you want to choose 3
items
Mathematically
>>> math.factorial(9) // (math.factorial(3) * math.factorial(6))
84
This is the definition of combinations
_____n!_____
k!(n - k)!
So as a general function
def num_combinations(n, k):
returnmath.factorial(n) // (math.factorial(k), math.factorial(n-k))
Brute force
>>>len(list(itertools.combinations(range(1,10), 3)))
84
Post a Comment for "How To Calculate The Number Of All Possible Combinations For A Range Of Numbers From 1 To N?"