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

标签 python math combinations python-itertools

除此之外:

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 :

enter image description here

对于所有组合:

enter image description here

关于python - 如何计算从 1 到 N 的一系列数字的所有可能组合的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30847280/

相关文章:

javascript - 如何将一个向量旋转到另一个向量上?

regex - 如何创建一个正则表达式来查找任意组合中的单词?

python - Python中List的组合项

python - 将列表分成随机大小的 block 的最佳方法?

python - 如何使用元素树测试 XML 节点是否具有特定字符串

php - 为什么计算 1/(n * log(n) - n) 会破坏计算机?

php - 多次回显一个 PHP 变量

algorithm - 对总和有限制的安排

python - 绘图中的对数色标

python - vim 和 conque gdb 插件的问题