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

僤鯓⒐⒋嵵緔 提交于 2019-12-24 11:32:25

问题


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?


回答1:


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 :

and for all combinations :




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

Brute force

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


来源:https://stackoverflow.com/questions/30847280/how-to-calculate-the-number-of-all-possible-combinations-for-a-range-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!