num_permutations: 创建 k 个元素的子序列的排列数

一个函数,用于计算从包含 n 个元素的序列中创建包含 k 个元素的子序列的排列数。

from mlxtend.math import num_permutations

概述

排列是指从集合中选取项目时考虑其出现的顺序(与组合不同)。例如,考虑从包含 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 是“相同的组合”,但却是不同的排列——在组合中顺序不重要,但在排列中顺序很重要。

从大小为 n 的集合中组合元素(无放回)形成大小为 k 的子集的数量通过二项式系数(“从 n 中选 k”)计算

要计算有放回的排列数,我们只需计算.

参考文献

示例 1 - 计算排列数

from mlxtend.math import num_permutations

c = num_permutations(n=20, k=8, with_replacement=False)
print('Number of ways to permute 20 elements'
      ' into 8 subelements: %d' % c)
Number of ways to permute 20 elements into 8 subelements: 5079110400
from mlxtend.math import num_permutations

c = num_permutations(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): 25600000000

示例 2 - 进度跟踪用例

跟踪计算密集型任务的进度以估计其运行时间通常非常有用。这里,可以使用 num_combination 函数来计算 itertools 中 permutations 可迭代对象的最大循环次数

import itertools
import sys
import time
from mlxtend.math import num_permutations

items = {1, 2, 3, 4, 5, 6, 7, 8}
max_iter = num_permutations(n=len(items), k=3, 
                            with_replacement=False)

for idx, i in enumerate(itertools.permutations(items, r=3)):
    # do some computation with itemset i
    time.sleep(0.01)
    sys.stdout.write('\rProgress: %d/%d' % (idx + 1, max_iter))
    sys.stdout.flush()
Progress: 336/336

API

num_permutations(n, k, with_replacement=False)

计算可能排列数的函数。

参数

  • n : int

    项目总数。

  • k : int

    目标项目集中的元素数。

  • with_replacement : bool

    如果为 True,则允许重复元素。

返回值

  • permut : int

    可能排列数。

示例

有关用法示例,请参见 https://mlxtend.cn/mlxtend/user_guide/math/num_permutations/