简体   繁体   English

在 Python 中计算排列

[英]Counting permuations in Python

What is the fastest way of counting the number of permutations?计算排列数的最快方法是什么? I have the following problem:我有以下问题:

First I have this:首先我有这个:

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')

The aim is to go through each one and calculate the number of permutations that each one has and construct an array with these values.目的是遍历每一个并计算每个排列的数量,并用这些值构造一个数组。 I implemented this using:我使用以下方法实现了这一点:

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

np.asanyarray(j) converts the ('a1','a1','a1') into formal ['a1','a1', 'a1'] which is need for permutations() to work. np.asanyarray(j) 将 ('a1','a1','a1') 转换为正式的 ['a1','a1', 'a1'] ,这是 permutations() 工作所需的。 set erases the permutations which are identical. set 删除相同的排列。 list makes a list of this. list 列出了这个。 len calculates how many permutations can i make with a1, a1, a1. len 计算我可以用 a1、a1、a1 进行多少排列。

So basically all I want is to count the number of permutations... However my code is extremely!!!所以基本上我想要的只是计算排列的数量......但是我的代码非常!!! slow !慢 ! Thank you!谢谢!

Use math.使用数学。 The number of permutations of a list is the factorial of the length of the list, divided by the product of the factorials of the multiplicity of each element (since sets of repeated elements are permuted with no effect).列表的排列数是列表长度的阶乘除以每个元素的多重性的阶乘的乘积(因为重复元素的集合没有影响)。

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

Examples:例子:

>>> npermutations([1,1,1])
1
>>> npermutations([1,2,3])
6
>>> npermutations([1,3,1,2,1,3,1,2])
420

If you want permutations with replacement, this exists and is called the cartesian product.如果你想要置换置换,这存在并且被称为笛卡尔积。 Itertools has a function for this, product() : Itertools 有一个功能, product()

>>> for i in itertools.product('ABC', repeat=3):
...     print i
...
('A', 'A', 'A')
('A', 'A', 'B')
('A', 'A', 'C')
('A', 'B', 'A')
('A', 'B', 'B')
('A', 'B', 'C')
('A', 'C', 'A')
('A', 'C', 'B')
('A', 'C', 'C')
('B', 'A', 'A')
('B', 'A', 'B')
('B', 'A', 'C')
('B', 'B', 'A')
('B', 'B', 'B')
('B', 'B', 'C')
('B', 'C', 'A')
('B', 'C', 'B')
('B', 'C', 'C')
('C', 'A', 'A')
('C', 'A', 'B')
('C', 'A', 'C')
('C', 'B', 'A')
('C', 'B', 'B')
('C', 'B', 'C')
('C', 'C', 'A')
('C', 'C', 'B')
('C', 'C', 'C')

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

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