简体   繁体   中英

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). In this sample case, there will be 4 permutations equal to the original array. Well that's what I get using itertools.permutations in python. Anyone with something faster? I will be most grateful. Following is my so slow python code.

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. 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! * 2! * 1! * 1! = 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

For N elements, the number of possible permutation is N!

If you have in example [5, 5, 5, 4, 1], there is 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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