From d73035c1d7280325790323d21374626f021516ba Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 6 Feb 2025 18:35:55 -0600 Subject: [PATCH] Add multinomial to the itertools recipes docs (gh-129760) (cherry picked from commit e1e85204edbf8c0c9ba1e50c74ac8708553585d8) Co-authored-by: Raymond Hettinger --- Doc/library/itertools.rst | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index e487fc4d553580..8e78ae9cc00f0b 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -838,10 +838,10 @@ and :term:`generators ` 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: