简体   繁体   English

列表的所有可能排列中的排序元素数(排列)

[英]Number of sorted elements (permutations), in all possible permutations of a list

Given an array, say, arr = [5, 5, 4, 4, 2, 1] , how can I find, of all possible permutations of this array, the number of permutations which are same like the original array itself (assuming the original array is always sorted in descending order). 给定一个数组,比如, arr = [5, 5, 4, 4, 2, 1] ,如何找到这个数组的所有可能排列,与原始数组本身相同的排列数(假设原始数组始终按降序排序)。 In this sample case, there will be 4 permutations equal to the original array. 在此示例中,将有4个排列等于原始数组。 Well that's what I get using itertools.permutations in python. 那就是我在python中使用itertools.permutations得到的东西。 Anyone with something faster? 谁有更快的东西? I will be most grateful. 我将非常感激。 Following is my so slow python code. 以下是我那么慢的python代码。

from itertools import permutations

arr = sorted(map(int, (raw_input().split())), reverse = True)

perms = permutations(n,len(arr))

cnt = 0;

for i in perms:
    if list(i) == arr: print i; cnt += 1
print cnt

Say your array is size n and the repetitions are r1, r2, ..., rk, so that sum(ri) = n. 假设您的数组大小为n,重复次数为r1,r2,...,rk,因此sum(ri)= n。 Then the answer is the product of the factorials of the repetitions. 然后答案是重复的阶乘的产物。

eg, for arr = [5, 5, 4, 4, 2, 1], we get r = [2, 2, 1, 1], and an answer of 2! 例如,对于arr = [5,5,4,4,2,1],我们得到r = [2,2,1,1],答案为2! * 2! * 2! * 1! * 1! * 1! * 1! = 4 = 4

You can get the product of the factorials of the lengths of all same-value subsequences: 您可以获得所有相同值子序列长度的阶乘的乘积:

from itertools import groupby
from functools import reduce
from math import factorial
from operator import mul
print(reduce(mul, map(lambda t: factorial(sum(1 for i in t[1])), groupby(arr))))

This outputs: 4 这输出: 4

For N elements, the number of possible permutation is N! 对于N个元素,可能的排列数是N!

If you have in example [5, 5, 5, 4, 1], there is 3! 如果你有例子[5,5,5,4,1],那就有3个! permutations where the array is the same. 阵列相同的排列。

I'd loop the array and store in a associated array the value and the number of that value was met. 我将循环数组并在关联数组中存储值和该值的数量。

Pseudo-code : 伪码

firstArray = [5, 5, 4, 4, 2, 1]
doubleArray = []

for each item in firstArray:
    if item is in doubleArray keys:
        doubleArray[item]++
    else:
        doubleArray[item] = 1

result = 1
for each elem in doubleArray:
    result *= fact(elem)

print "There is " + elem + " permutations possible where the original array remains the same"

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

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