简体   繁体   English

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

[英]How to calculate the number of unique permutations without building a temporary list?

How to calculate this number instead of enumerate all permutations and then create set to cut off all repetitions? 如何计算这个数字而不是枚举所有排列,然后创建集合以切断所有重复?

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

len(set(itertools.permutations('aabb')))
6

Let counts be an array with counts[k] = count of the k'th symbol. 令count为数组,其中count [k] =第k个符号的计数。

We'll need a way for python to easily compute a bunch of multiplications, a product() function.... 我们需要一种方法让python轻松计算一堆乘法,一个product()函数....

From What's the Python function like sum() but for multiplication? 什么是Python函数,如sum(),但乘法? product()? 产品()? :

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

def product(X):
    return reduce(operator.mul, X, 1)

Now we can define the number of permutations as: 现在我们可以将排列数定义为:

def unique_permutations(counts):
    return math.factorial(sum(counts))/product(map(math.factorial, counts))

Now in another language, one would have to worry about the large numbers that can appear in this division as the result of taking large factorials or multiplying numerous smaller factorials. 现在用另一种语言,人们不得不担心这个部门中出现的大数字是由于采用大因子或乘以许多较小的因子。 Normally, at some point the calculation will overflow a MAXINT or MAXFLOAT spec. 通常,在某些时候,计算将溢出MAXINT或MAXFLOAT规范。 But in python, all integer operations are exact, taking as many digits as required, and integer overflow will not occur by design. 但是在python中,所有整数运算都是精确的,占用了所需数量的数字,并且设计不会发生整数溢出。 Speed might become an issue, but that is a different matter. 速度可能会成为一个问题,但这是另一回事。

How to use it: 如何使用它:

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

>>> unique_permutations([2,2])
6

For the math of how to do this, see Wikipedia: Permutation: Permutations of Multisets 有关如何执行此操作的数学,请参阅Wikipedia:Permutation:Multisets的排列

If you have N_i copies of each letter then the number you want is the multinomial coefficient 如果你有每个字母的N_i副本,那么你想要的数字是多项系数

(N_1 + N_2 + ... + N_k)!/(N_1! N_2! ... N_k!)

For methods for computing this without overflow, see How do I compute multinomials efficiently? 对于没有溢出计算的方法,请参阅如何有效地计算多项式? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM