[英]How to calculate the number of unique permutations without building a temporary list?
如何計算這個數字而不是枚舉所有排列,然后創建集合以切斷所有重復?
len(set(itertools.permutations('aaabbb')))
20
len(set(itertools.permutations('aabb')))
6
令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)
現在我們可以將排列數定義為:
def unique_permutations(counts):
return math.factorial(sum(counts))/product(map(math.factorial, counts))
現在用另一種語言,人們不得不擔心這個部門中出現的大數字是由於采用大因子或乘以許多較小的因子。 通常,在某些時候,計算將溢出MAXINT或MAXFLOAT規范。 但是在python中,所有整數運算都是精確的,占用了所需數量的數字,並且設計不會發生整數溢出。 速度可能會成為一個問題,但這是另一回事。
如何使用它:
>>> unique_permutations([3,3])
20
>>> unique_permutations([2,2])
6
有關如何執行此操作的數學,請參閱Wikipedia:Permutation:Multisets的排列
如果你有每個字母的N_i
副本,那么你想要的數字是多項系數
(N_1 + N_2 + ... + N_k)!/(N_1! N_2! ... N_k!)
對於沒有溢出計算的方法,請參閱如何有效地計算多項式? 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.