How to calculate the number of all possible combinations for a range of numbers from 1 to N?

3.4k views Asked by At

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)):
            yield f
x = range(1,18)
len(list(brute_force(x)))

[out]:

131071
  • How could I mathematically calculate the number of all possible combinations?

  • Is there a way to do it computationally without enumerating the possible combinations?

2

There are 2 answers

4
Mazdak On BEST ANSWER

Always there is 2n−1 non-empty subset of set {1,...,n}.

For example consider the list ['a','b','c']:

>>> [list(combinations(['a','b','c'],i)) for i in range(1,4)]
[[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'), ('b', 'c')], [('a', 'b', 'c')]]
>>> l=[list(combinations(['a','b','c'],i)) for i in range(1,4)]
>>> sum(map(len,l))
7

That the length of our list is 3 so we have 23-1=7 combinations.

And for a range(10) :

>>> l=[list(combinations(range(10),i)) for i in range(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 :

enter image description here

and for all combinations :

enter image description here

1
Cory Kramer On

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):
    return math.factorial(n) // (math.factorial(k), math.factorial(n-k))

Brute force

>>> len(list(itertools.combinations(range(1,10), 3)))
84