Counting permuations in Python

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

Tags:

Python