![](/img/trans.png)
[英]How do I get all n! combinations of possible lists that can be created from numbers 1 to n?
[英]How to calculate the number of all possible combinations for a range of numbers from 1 to N?
除了这样做:
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
如何数学计算所有可能组合的数量?
有没有一种方法可以在不枚举可能的组合的情况下进行计算?
总是存在集合{1,...,n}
2 n -1个非空子集。
例如,考虑列表['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,所以我们有2 3 -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
。
实际上是从数学角度来看的:
集合的k组合是S的k个不同元素的子集。如果集合具有n个元素,则k组合的数量等于二项式系数 :
对于所有组合:
假设您有[1, 10)
1,10)中的列表,并且想要选择3
项目
数学上
>>> math.factorial(9) // (math.factorial(3) * math.factorial(6))
84
这是组合的定义
_____n!_____
k!(n - k)!
因此作为一般功能
def num_combinations(n, k):
return math.factorial(n) // (math.factorial(k), math.factorial(n-k))
蛮力
>>> len(list(itertools.combinations(range(1,10), 3)))
84
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.