Skip to main content
 首页 » 编程设计

python之如何计算从 1 到 N 的一系列数字的所有可能组合的数量

2025年05月04日10over140

除此之外:

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))) 

[输出]:

131071 
  • 我如何从数学上计算出所有可能组合的数量?

  • 有没有一种方法可以在不枚举可能的组合的情况下进行计算?

请您参考如下方法:

总有 2n−1 集合 {1,...,n} 的非空子集。

例如考虑列表['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 

我们列表的长度是 3,所以我们有 23-1=7 种组合。

对于 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 

请注意,如果您想计算空子集,您可以使用 2^n。

其实从数学的角度来看:

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 :

对于所有组合: