num_combinations: 创建 k 个元素子序列的组合
一个函数,用于计算从包含 n 个元素的序列中创建 k 个元素子序列的组合数。
from mlxtend.math import num_combinations
概述
组合是从集合中选取项目,不考虑其出现的顺序(与排列不同)。例如,考虑从一个包含 5 个元素(n=5)的集合中选择 3 个元素(k=3)的组合
- 集合: {1, 2, 3, 4, 5}
- 组合 1a: {1, 3, 5}
- 组合 1b: {1, 5, 3}
- 组合 1c: {3, 5, 1}
- ...
- 组合 2: {1, 3, 4}
在上面的例子中,组合 1a、1b 和 1c 是“同一个组合”,并被计为“组合项目 1、3 和 5 的 1 种可能方式”——在组合中,顺序不重要。
从大小为 n 的集合中组合元素(无放回)形成大小为 k 的子集的方式数,通过二项式系数(“n 选 k”)计算得到
要计算有放回的组合数,使用以下替代公式(“n 多重选择 k”)
参考资料
示例 1 - 计算组合数
from mlxtend.math import num_combinations
c = num_combinations(n=20, k=8, with_replacement=False)
print('Number of ways to combine 20 elements'
' into 8 subelements: %d' % c)
Number of ways to combine 20 elements into 8 subelements: 125970
from mlxtend.math import num_combinations
c = num_combinations(n=20, k=8, with_replacement=True)
print('Number of ways to combine 20 elements'
' into 8 subelements (with replacement): %d' % c)
Number of ways to combine 20 elements into 8 subelements (with replacement): 2220075
示例 2 - 进度跟踪用例
跟踪计算密集型任务的进度以估算其运行时间通常非常有用。在这里,num_combination
函数可用于计算 itertools 中 combinations
可迭代对象的最大循环次数
import itertools
import sys
import time
from mlxtend.math import num_combinations
items = {1, 2, 3, 4, 5, 6, 7, 8}
max_iter = num_combinations(n=len(items), k=3,
with_replacement=False)
for idx, i in enumerate(itertools.combinations(items, r=3)):
# do some computation with itemset i
time.sleep(0.1)
sys.stdout.write('\rProgress: %d/%d' % (idx + 1, max_iter))
sys.stdout.flush()
Progress: 56/56
API
num_combinations(n, k, with_replacement=False)
计算可能组合数的函数。
参数
-
n
:int
项目总数。
-
k
:int
目标项目集中的元素数量。
-
with_replacement
:bool
(默认值: False)如果为 True,则允许重复元素。
返回值
-
comb
:int
可能组合的数量。
示例
有关用法示例,请参见 https://mlxtend.cn/mlxtend/user_guide/math/num_combinations/