]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] Add multinomial to the itertools recipes docs (gh-129760) (gh-129854)
authorBénédikt Tran <10796600+picnixz@users.noreply.github.com>
Sat, 8 Feb 2025 14:10:41 +0000 (15:10 +0100)
committerGitHub <noreply@github.com>
Sat, 8 Feb 2025 14:10:41 +0000 (08:10 -0600)
Doc/library/itertools.rst

index a82fd8630b7b6aa8f25ec0a8f66bc6050e6fbdb0..b1b7b630a5ecbb574801669e2e505480a3a65c98 100644 (file)
@@ -1082,6 +1082,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 math.prod(map(math.comb, accumulate(counts), counts))
+
 
 .. doctest::
     :hide:
@@ -1644,6 +1650,12 @@ The following recipes have a more mathematical flavor:
     >>> ''.join(it)
     'DEF1'
 
+    >>> multinomial(5, 2, 1, 1, 2)
+    83160
+    >>> word = 'coffee'
+    >>> multinomial(*collections.Counter(word).values()) == len(set(permutations(word)))
+    True
+
 
 .. testcode::
     :hide: