]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Add multinomial to the itertools recipes docs (gh-129760)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Fri, 7 Feb 2025 00:35:55 +0000 (18:35 -0600)
committerGitHub <noreply@github.com>
Fri, 7 Feb 2025 00:35:55 +0000 (18:35 -0600)
Doc/library/itertools.rst

index eb61453718bd3c0a71d2a8975782ef5d7d9c63f6..fbbec42ce9dae71cf84cb6b9b2c1a86b9ebc53cc 100644 (file)
@@ -838,10 +838,10 @@ and :term:`generators <generator>` which incur interpreter overhead.
 
 .. testcode::
 
-   from collections import deque
+   from collections import Counter, deque
    from contextlib import suppress
    from functools import reduce
-   from math import sumprod, isqrt
+   from math import comb, prod, sumprod, isqrt
    from operator import itemgetter, getitem, mul, neg
 
    def take(n, iterable):
@@ -1127,6 +1127,12 @@ The following recipes have a more mathematical flavor:
            n -= n // prime
        return n
 
+   def multinomial(*counts):
+       "Number of distinct arrangements of a multiset."
+       # Counter('abracadabra').values() -> 5 2 1 1 2
+       # multinomial(5, 2, 1, 1, 2) → 83160
+       return prod(map(comb, accumulate(counts), counts))
+
 
 .. doctest::
     :hide:
@@ -1730,6 +1736,12 @@ The following recipes have a more mathematical flavor:
     >>> ''.join(it)
     'DEF1'
 
+    >>> multinomial(5, 2, 1, 1, 2)
+    83160
+    >>> word = 'coffee'
+    >>> multinomial(*Counter(word).values()) == len(set(permutations(word)))
+    True
+
 
 .. testcode::
     :hide: