计算Python中的permeations

Oni*_*olo 3 python

计算排列数的最快方法是什么?我有以下问题:

首先我有这个:

ncombos = itertools.combinations_with_replacement(['a1', 'a2', 'a3'], years*n)
('a1', 'a1', 'a1')
('a1', 'a1', 'a2')
('a1', 'a1', 'a3')
('a1', 'a2', 'a2')
.... etc.....    
('a3', 'a3', 'a3')
Run Code Online (Sandbox Code Playgroud)

目的是遍历每一个并计算每个人拥有的排列数,并用这些值构造一个数组.我用这个实现了:

nodes = np.ones(len(leafs)); i=0  #This will store the number of permutations

for j in ncombos:
    nodes[i] =len(list(set(itertools.permutations(np.asanyarray(j), n))))
    i = i+1
Run Code Online (Sandbox Code Playgroud)

np.asanyarray(j)将('a1','a1','a1')转换为正式['a1','a1','a1'],这需要排列()才能工作.集擦除了相同的排列.列表列出了这个.len计算我可以使用a1,a1,a1进行多少排列.

所以基本上我想要的只是计算排列的数量...但是我的代码非常!!! 慢 !谢谢!

nne*_*neo 13

用数学.列表的排列数是列表长度的阶乘,除以每个元素的多重性的阶乘的乘积(因为重复元素的集合被置换而没有效果).

import operator
from collections import Counter
from math import factorial
def npermutations(l):
    num = factorial(len(l))
    mults = Counter(l).values()
    den = reduce(operator.mul, (factorial(v) for v in mults), 1)
    return num / den
Run Code Online (Sandbox Code Playgroud)

例子:

>>> npermutations([1,1,1])
1
>>> npermutations([1,2,3])
6
>>> npermutations([1,3,1,2,1,3,1,2])
420
Run Code Online (Sandbox Code Playgroud)