[英]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)):
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? 有没有一种方法可以在不枚举可能的组合的情况下进行计算?
Always there is 2 n −1 non-empty subset of set {1,...,n}
. 总是存在集合
{1,...,n}
2 n -1个非空子集。
For example consider the list ['a','b','c']
: 例如,考虑列表
['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 2 3 -1=7 combinations. 我们列表的长度是3,所以我们有2 3 -1 = 7个组合。
And for a range(10)
: 并且对于
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
. 注意,如果要计算空子集,则可以使用
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 :
集合的k组合是S的k个不同元素的子集。如果集合具有n个元素,则k组合的数量等于二项式系数 :
and for all combinations : 对于所有组合:
Assuming you have a list from [1, 10)
, and you want to choose 3
items 假设您有
[1, 10)
1,10)中的列表,并且想要选择3
项目
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.