如何在不构建临时列表的情况下计算唯一排列的数量?

Pin*_*niu 4 python math combinatorics

如何计算这个数字而不是枚举所有排列,然后创建集合以切断所有重复?

len(set(itertools.permutations('aaabbb')))
20

len(set(itertools.permutations('aabb')))
6
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 7

令count为数组,其中count [k] =第k个符号的计数.

我们需要一种方法让python轻松计算一堆乘法,一个product()函数....

什么是Python函数,如sum(),但乘法?产品()?:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

def product(X):
    return reduce(operator.mul, X, 1)
Run Code Online (Sandbox Code Playgroud)

现在我们可以将排列数定义为:

def unique_permutations(counts):
    return math.factorial(sum(counts))/product(map(math.factorial, counts))
Run Code Online (Sandbox Code Playgroud)

现在用另一种语言,人们不得不担心这个部门中出现的大数字是由于采用大因子或乘以许多较小的因子.通常,在某些时候,计算将溢出MAXINT或MAXFLOAT规范.但是在python中,所有整数运算都是精确的,占用了所需数量的数字,并且设计不会发生整数溢出.速度可能会成为一个问题,但这是另一回事.

如何使用它:

>>> unique_permutations([3,3])
20

>>> unique_permutations([2,2])
6
Run Code Online (Sandbox Code Playgroud)

有关如何执行此操作的数学,请参阅Wikipedia:Permutation:Multisets的排列