@@ -1981,6 +1981,175 @@ msgid ""
19811981" while True:\n"
19821982" yield function()"
19831983msgstr ""
1984+ "from collections import Counter, deque\n"
1985+ "from contextlib import suppress\n"
1986+ "from functools import reduce\n"
1987+ "from math import comb, prod, sumprod, isqrt\n"
1988+ "from operator import itemgetter, getitem, mul, neg\n"
1989+ "\n"
1990+ "def take(n, iterable):\n"
1991+ " \" Return first n items of the iterable as a list.\" \n"
1992+ " return list(islice(iterable, n))\n"
1993+ "\n"
1994+ "def prepend(value, iterable):\n"
1995+ " \" Prepend a single value in front of an iterable.\" \n"
1996+ " # prepend(1, [2, 3, 4]) → 1 2 3 4\n"
1997+ " return chain([value], iterable)\n"
1998+ "\n"
1999+ "def tabulate(function, start=0):\n"
2000+ " \" Return function(0), function(1), ...\" \n"
2001+ " return map(function, count(start))\n"
2002+ "\n"
2003+ "def repeatfunc(function, times=None, *args):\n"
2004+ " \" Repeat calls to a function with specified arguments.\" \n"
2005+ " if times is None:\n"
2006+ " return starmap(function, repeat(args))\n"
2007+ " return starmap(function, repeat(args, times))\n"
2008+ "\n"
2009+ "def flatten(list_of_lists):\n"
2010+ " \" Flatten one level of nesting.\" \n"
2011+ " return chain.from_iterable(list_of_lists)\n"
2012+ "\n"
2013+ "def ncycles(iterable, n):\n"
2014+ " \" Returns the sequence elements n times.\" \n"
2015+ " return chain.from_iterable(repeat(tuple(iterable), n))\n"
2016+ "\n"
2017+ "def loops(n):\n"
2018+ " \" Loop n times. Like range(n) but without creating integers.\" \n"
2019+ " # for _ in loops(100): ...\n"
2020+ " return repeat(None, n)\n"
2021+ "\n"
2022+ "def tail(n, iterable):\n"
2023+ " \" Return an iterator over the last n items.\" \n"
2024+ " # tail(3, 'ABCDEFG') → E F G\n"
2025+ " return iter(deque(iterable, maxlen=n))\n"
2026+ "\n"
2027+ "def consume(iterator, n=None):\n"
2028+ " \" Advance the iterator n-steps ahead. If n is None, consume entirely.\" \n"
2029+ " # Use functions that consume iterators at C speed.\n"
2030+ " if n is None:\n"
2031+ " deque(iterator, maxlen=0)\n"
2032+ " else:\n"
2033+ " next(islice(iterator, n, n), None)\n"
2034+ "\n"
2035+ "def nth(iterable, n, default=None):\n"
2036+ " \" Returns the nth item or a default value.\" \n"
2037+ " return next(islice(iterable, n, None), default)\n"
2038+ "\n"
2039+ "def quantify(iterable, predicate=bool):\n"
2040+ " \" Given a predicate that returns True or False, count the True results."
2041+ "\" \n"
2042+ " return sum(map(predicate, iterable))\n"
2043+ "\n"
2044+ "def first_true(iterable, default=False, predicate=None):\n"
2045+ " \" Returns the first true value or the *default* if there is no true "
2046+ "value.\" \n"
2047+ " # first_true([a,b,c], x) → a or b or c or x\n"
2048+ " # first_true([a,b], x, f) → a if f(a) else b if f(b) else x\n"
2049+ " return next(filter(predicate, iterable), default)\n"
2050+ "\n"
2051+ "def all_equal(iterable, key=None):\n"
2052+ " \" Returns True if all the elements are equal to each other.\" \n"
2053+ " # all_equal('4٤௪౪໔', key=int) → True\n"
2054+ " return len(take(2, groupby(iterable, key))) <= 1\n"
2055+ "\n"
2056+ "def unique_justseen(iterable, key=None):\n"
2057+ " \" Yield unique elements, preserving order. Remember only the element "
2058+ "just seen.\" \n"
2059+ " # unique_justseen('AAAABBBCCDAABBB') → A B C D A B\n"
2060+ " # unique_justseen('ABBcCAD', str.casefold) → A B c A D\n"
2061+ " if key is None:\n"
2062+ " return map(itemgetter(0), groupby(iterable))\n"
2063+ " return map(next, map(itemgetter(1), groupby(iterable, key)))\n"
2064+ "\n"
2065+ "def unique_everseen(iterable, key=None):\n"
2066+ " \" Yield unique elements, preserving order. Remember all elements ever "
2067+ "seen.\" \n"
2068+ " # unique_everseen('AAAABBBCCDAABBB') → A B C D\n"
2069+ " # unique_everseen('ABBcCAD', str.casefold) → A B c D\n"
2070+ " seen = set()\n"
2071+ " if key is None:\n"
2072+ " for element in filterfalse(seen.__contains__, iterable):\n"
2073+ " seen.add(element)\n"
2074+ " yield element\n"
2075+ " else:\n"
2076+ " for element in iterable:\n"
2077+ " k = key(element)\n"
2078+ " if k not in seen:\n"
2079+ " seen.add(k)\n"
2080+ " yield element\n"
2081+ "\n"
2082+ "def unique(iterable, key=None, reverse=False):\n"
2083+ " \" Yield unique elements in sorted order. Supports unhashable inputs.\" \n"
2084+ " # unique([[1, 2], [3, 4], [1, 2]]) → [1, 2] [3, 4]\n"
2085+ " sequenced = sorted(iterable, key=key, reverse=reverse)\n"
2086+ " return unique_justseen(sequenced, key=key)\n"
2087+ "\n"
2088+ "def sliding_window(iterable, n):\n"
2089+ " \" Collect data into overlapping fixed-length chunks or blocks.\" \n"
2090+ " # sliding_window('ABCDEFG', 4) → ABCD BCDE CDEF DEFG\n"
2091+ " iterator = iter(iterable)\n"
2092+ " window = deque(islice(iterator, n - 1), maxlen=n)\n"
2093+ " for x in iterator:\n"
2094+ " window.append(x)\n"
2095+ " yield tuple(window)\n"
2096+ "\n"
2097+ "def grouper(iterable, n, *, incomplete='fill', fillvalue=None):\n"
2098+ " \" Collect data into non-overlapping fixed-length chunks or blocks.\" \n"
2099+ " # grouper('ABCDEFG', 3, fillvalue='x') → ABC DEF Gxx\n"
2100+ " # grouper('ABCDEFG', 3, incomplete='strict') → ABC DEF ValueError\n"
2101+ " # grouper('ABCDEFG', 3, incomplete='ignore') → ABC DEF\n"
2102+ " iterators = [iter(iterable)] * n\n"
2103+ " match incomplete:\n"
2104+ " case 'fill':\n"
2105+ " return zip_longest(*iterators, fillvalue=fillvalue)\n"
2106+ " case 'strict':\n"
2107+ " return zip(*iterators, strict=True)\n"
2108+ " case 'ignore':\n"
2109+ " return zip(*iterators)\n"
2110+ " case _:\n"
2111+ " raise ValueError('Expected fill, strict, or ignore')\n"
2112+ "\n"
2113+ "def roundrobin(*iterables):\n"
2114+ " \" Visit input iterables in a cycle until each is exhausted.\" \n"
2115+ " # roundrobin('ABC', 'D', 'EF') → A D E B F C\n"
2116+ " # Algorithm credited to George Sakkis\n"
2117+ " iterators = map(iter, iterables)\n"
2118+ " for num_active in range(len(iterables), 0, -1):\n"
2119+ " iterators = cycle(islice(iterators, num_active))\n"
2120+ " yield from map(next, iterators)\n"
2121+ "\n"
2122+ "def subslices(seq):\n"
2123+ " \" Return all contiguous non-empty subslices of a sequence.\" \n"
2124+ " # subslices('ABCD') → A AB ABC ABCD B BC BCD C CD D\n"
2125+ " slices = starmap(slice, combinations(range(len(seq) + 1), 2))\n"
2126+ " return map(getitem, repeat(seq), slices)\n"
2127+ "\n"
2128+ "def iter_index(iterable, value, start=0, stop=None):\n"
2129+ " \" Return indices where a value occurs in a sequence or iterable.\" \n"
2130+ " # iter_index('AABCADEAF', 'A') → 0 1 4 7\n"
2131+ " seq_index = getattr(iterable, 'index', None)\n"
2132+ " if seq_index is None:\n"
2133+ " iterator = islice(iterable, start, stop)\n"
2134+ " for i, element in enumerate(iterator, start):\n"
2135+ " if element is value or element == value:\n"
2136+ " yield i\n"
2137+ " else:\n"
2138+ " stop = len(iterable) if stop is None else stop\n"
2139+ " i = start\n"
2140+ " with suppress(ValueError):\n"
2141+ " while True:\n"
2142+ " yield (i := seq_index(value, i, stop))\n"
2143+ " i += 1\n"
2144+ "\n"
2145+ "def iter_except(function, exception, first=None):\n"
2146+ " \" Convert a call-until-exception interface to an iterator interface.\" \n"
2147+ " # iter_except(d.popitem, KeyError) → non-blocking dictionary iterator\n"
2148+ " with suppress(exception):\n"
2149+ " if first is not None:\n"
2150+ " yield first()\n"
2151+ " while True:\n"
2152+ " yield function()"
19842153
19852154#: ../../library/itertools.rst:1008
19862155msgid "The following recipes have a more mathematical flavor:"
@@ -2112,3 +2281,126 @@ msgid ""
21122281" n -= n // prime\n"
21132282" return n"
21142283msgstr ""
2284+ "def multinomial(*counts):\n"
2285+ " \" Number of distinct arrangements of a multiset.\" \n"
2286+ " # Counter('abracadabra').values() → 5 2 2 1 1\n"
2287+ " # multinomial(5, 2, 2, 1, 1) → 83160\n"
2288+ " return prod(map(comb, accumulate(counts), counts))\n"
2289+ "\n"
2290+ "def powerset(iterable):\n"
2291+ " \" Subsequences of the iterable from shortest to longest.\" \n"
2292+ " # powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\n"
2293+ " s = list(iterable)\n"
2294+ " return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))\n"
2295+ "\n"
2296+ "def sum_of_squares(iterable):\n"
2297+ " \" Add up the squares of the input values.\" \n"
2298+ " # sum_of_squares([10, 20, 30]) → 1400\n"
2299+ " return sumprod(*tee(iterable))\n"
2300+ "\n"
2301+ "def reshape(matrix, columns):\n"
2302+ " \" Reshape a 2-D matrix to have a given number of columns.\" \n"
2303+ " # reshape([(0, 1), (2, 3), (4, 5)], 3) → (0, 1, 2), (3, 4, 5)\n"
2304+ " return batched(chain.from_iterable(matrix), columns, strict=True)\n"
2305+ "\n"
2306+ "def transpose(matrix):\n"
2307+ " \" Swap the rows and columns of a 2-D matrix.\" \n"
2308+ " # transpose([(1, 2, 3), (11, 22, 33)]) → (1, 11) (2, 22) (3, 33)\n"
2309+ " return zip(*matrix, strict=True)\n"
2310+ "\n"
2311+ "def matmul(m1, m2):\n"
2312+ " \" Multiply two matrices.\" \n"
2313+ " # matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]) → (49, 80), (41, 60)\n"
2314+ " n = len(m2[0])\n"
2315+ " return batched(starmap(sumprod, product(m1, transpose(m2))), n)\n"
2316+ "\n"
2317+ "def convolve(signal, kernel):\n"
2318+ " \"\"\" Discrete linear convolution of two iterables.\n"
2319+ " Equivalent to polynomial multiplication.\n"
2320+ "\n"
2321+ " Convolutions are mathematically commutative; however, the inputs are\n"
2322+ " evaluated differently. The signal is consumed lazily and can be\n"
2323+ " infinite. The kernel is fully consumed before the calculations begin.\n"
2324+ "\n"
2325+ " Article: https://betterexplained.com/articles/intuitive-convolution/\n"
2326+ " Video: https://www.youtube.com/watch?v=KuXjwB4LzSA\n"
2327+ " \"\"\" \n"
2328+ " # convolve([1, -1, -20], [1, -3]) → 1 -4 -17 60\n"
2329+ " # convolve(data, [0.25, 0.25, 0.25, 0.25]) → Moving average (blur)\n"
2330+ " # convolve(data, [1/2, 0, -1/2]) → 1st derivative estimate\n"
2331+ " # convolve(data, [1, -2, 1]) → 2nd derivative estimate\n"
2332+ " kernel = tuple(kernel)[::-1]\n"
2333+ " n = len(kernel)\n"
2334+ " padded_signal = chain(repeat(0, n-1), signal, repeat(0, n-1))\n"
2335+ " windowed_signal = sliding_window(padded_signal, n)\n"
2336+ " return map(sumprod, repeat(kernel), windowed_signal)\n"
2337+ "\n"
2338+ "def polynomial_from_roots(roots):\n"
2339+ " \"\"\" Compute a polynomial's coefficients from its roots.\n"
2340+ "\n"
2341+ " (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60\n"
2342+ " \"\"\" \n"
2343+ " # polynomial_from_roots([5, -4, 3]) → [1, -4, -17, 60]\n"
2344+ " factors = zip(repeat(1), map(neg, roots))\n"
2345+ " return list(reduce(convolve, factors, [1]))\n"
2346+ "\n"
2347+ "def polynomial_eval(coefficients, x):\n"
2348+ " \"\"\" Evaluate a polynomial at a specific value.\n"
2349+ "\n"
2350+ " Computes with better numeric stability than Horner's method.\n"
2351+ " \"\"\" \n"
2352+ " # Evaluate x³ -4x² -17x + 60 at x = 5\n"
2353+ " # polynomial_eval([1, -4, -17, 60], x=5) → 0\n"
2354+ " n = len(coefficients)\n"
2355+ " if not n:\n"
2356+ " return type(x)(0)\n"
2357+ " powers = map(pow, repeat(x), reversed(range(n)))\n"
2358+ " return sumprod(coefficients, powers)\n"
2359+ "\n"
2360+ "def polynomial_derivative(coefficients):\n"
2361+ " \"\"\" Compute the first derivative of a polynomial.\n"
2362+ "\n"
2363+ " f(x) = x³ -4x² -17x + 60\n"
2364+ " f'(x) = 3x² -8x -17\n"
2365+ " \"\"\" \n"
2366+ " # polynomial_derivative([1, -4, -17, 60]) → [3, -8, -17]\n"
2367+ " n = len(coefficients)\n"
2368+ " powers = reversed(range(1, n))\n"
2369+ " return list(map(mul, coefficients, powers))\n"
2370+ "\n"
2371+ "def sieve(n):\n"
2372+ " \" Primes less than n.\" \n"
2373+ " # sieve(30) → 2 3 5 7 11 13 17 19 23 29\n"
2374+ " if n > 2:\n"
2375+ " yield 2\n"
2376+ " data = bytearray((0, 1)) * (n // 2)\n"
2377+ " for p in iter_index(data, 1, start=3, stop=isqrt(n) + 1):\n"
2378+ " data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))\n"
2379+ " yield from iter_index(data, 1, start=3)\n"
2380+ "\n"
2381+ "def factor(n):\n"
2382+ " \" Prime factors of n.\" \n"
2383+ " # factor(99) → 3 3 11\n"
2384+ " # factor(1_000_000_000_000_007) → 47 59 360620266859\n"
2385+ " # factor(1_000_000_000_000_403) → 1000000000000403\n"
2386+ " for prime in sieve(isqrt(n) + 1):\n"
2387+ " while not n % prime:\n"
2388+ " yield prime\n"
2389+ " n //= prime\n"
2390+ " if n == 1:\n"
2391+ " return\n"
2392+ " if n > 1:\n"
2393+ " yield n\n"
2394+ "\n"
2395+ "def is_prime(n):\n"
2396+ " \" Return True if n is prime.\" \n"
2397+ " # is_prime(1_000_000_000_000_403) → True\n"
2398+ " return n > 1 and next(factor(n)) == n\n"
2399+ "\n"
2400+ "def totient(n):\n"
2401+ " \" Count of natural numbers up to n that are coprime to n.\" \n"
2402+ " # https://mathworld.wolfram.com/TotientFunction.html\n"
2403+ " # totient(12) → 4 because len([1, 5, 7, 11]) == 4\n"
2404+ " for prime in set(factor(n)):\n"
2405+ " n -= n // prime\n"
2406+ " return n"
0 commit comments