Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/more_itertools/more.py: 19%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1__lazy_modules__ = frozenset({'queue', 'threading'})
3import math
4import types
6from collections import Counter, defaultdict, deque
7from collections.abc import Sequence
8from contextlib import suppress
9from functools import cached_property, partial, wraps
10from heapq import heapify, heapreplace
11from itertools import (
12 chain,
13 combinations,
14 compress,
15 count,
16 cycle,
17 dropwhile,
18 groupby,
19 islice,
20 permutations,
21 repeat,
22 starmap,
23 takewhile,
24 tee,
25 zip_longest,
26 product,
27)
28from math import comb, e, exp, floor, fsum, log, log1p, perm, tau
29from math import ceil, prod
30from queue import Empty, Queue
31from random import random, randrange, shuffle, uniform
32from operator import (
33 attrgetter,
34 getitem,
35 is_not,
36 itemgetter,
37 lt,
38 neg,
39 sub,
40 gt,
41)
42from sys import maxsize
43from time import monotonic
44from threading import Lock
46from .recipes import (
47 _marker,
48 consume,
49 first_true,
50 flatten,
51 is_prime,
52 nth,
53 powerset,
54 sieve,
55 take,
56 unique_everseen,
57 all_equal,
58 batched,
59)
61__all__ = [
62 'AbortThread',
63 'SequenceView',
64 'adjacent',
65 'all_unique',
66 'always_iterable',
67 'always_reversible',
68 'argmax',
69 'argmin',
70 'bucket',
71 'callback_iter',
72 'chunked',
73 'chunked_even',
74 'circular_shifts',
75 'classify_unique',
76 'collapse',
77 'combination_index',
78 'combination_with_replacement_index',
79 'concurrent_tee',
80 'consecutive_groups',
81 'constrained_batches',
82 'consumer',
83 'count_cycle',
84 'countable',
85 'derangements',
86 'dft',
87 'difference',
88 'distinct_combinations',
89 'distinct_permutations',
90 'distribute',
91 'divide',
92 'doublestarmap',
93 'duplicates_everseen',
94 'duplicates_justseen',
95 'exactly_n',
96 'extract',
97 'filter_except',
98 'filter_map',
99 'first',
100 'gray_product',
101 'groupby_transform',
102 'ichunked',
103 'idft',
104 'iequals',
105 'ilen',
106 'interleave',
107 'interleave_evenly',
108 'interleave_longest',
109 'interleave_randomly',
110 'intersperse',
111 'is_sorted',
112 'islice_extended',
113 'iter_suppress',
114 'iterate',
115 'join_mappings',
116 'last',
117 'locate',
118 'longest_common_prefix',
119 'lstrip',
120 'make_decorator',
121 'map_except',
122 'map_if',
123 'map_reduce',
124 'mark_ends',
125 'minmax',
126 'nth_combination_with_replacement',
127 'nth_or_last',
128 'nth_permutation',
129 'nth_prime',
130 'nth_product',
131 'numeric_range',
132 'one',
133 'only',
134 'outer_product',
135 'padded',
136 'partial_product',
137 'partitions',
138 'peekable',
139 'permutation_index',
140 'powerset_of_sets',
141 'product_index',
142 'raise_',
143 'random_ordered_range',
144 'repeat_each',
145 'repeat_last',
146 'replace',
147 'rlocate',
148 'rstrip',
149 'run_length',
150 'sample',
151 'seekable',
152 'serialize',
153 'set_partitions',
154 'side_effect',
155 'sized_iterator',
156 'sliced',
157 'sort_together',
158 'split_after',
159 'split_at',
160 'split_before',
161 'split_into',
162 'split_when',
163 'spy',
164 'stagger',
165 'strictly_n',
166 'strip',
167 'subfactorial',
168 'substrings',
169 'substrings_indexes',
170 'synchronized',
171 'takewhile_inclusive',
172 'time_limited',
173 'unique_in_window',
174 'unique_to_each',
175 'unzip',
176 'value_chain',
177 'windowed',
178 'windowed_complete',
179 'with_iter',
180 'zip_broadcast',
181 'zip_offset',
182]
184# math.sumprod is available for Python 3.12+
185try:
186 from math import sumprod as _fsumprod
188except ImportError: # pragma: no cover
189 # Extended precision algorithms from T. J. Dekker,
190 # "A Floating-Point Technique for Extending the Available Precision"
191 # https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
192 # Formulas: (5.5) (5.6) and (5.8). Code: mul12()
194 def dl_split(x: float):
195 "Split a float into two half-precision components."
196 t = x * 134217729.0 # Veltkamp constant = 2.0 ** 27 + 1
197 hi = t - (t - x)
198 lo = x - hi
199 return hi, lo
201 def dl_mul(x, y):
202 "Lossless multiplication."
203 xx_hi, xx_lo = dl_split(x)
204 yy_hi, yy_lo = dl_split(y)
205 p = xx_hi * yy_hi
206 q = xx_hi * yy_lo + xx_lo * yy_hi
207 z = p + q
208 zz = p - z + q + xx_lo * yy_lo
209 return z, zz
211 def _fsumprod(p, q):
212 return fsum(chain.from_iterable(map(dl_mul, p, q)))
215def chunked(iterable, n, strict=False):
216 """Break *iterable* into lists of length *n*:
218 >>> list(chunked([1, 2, 3, 4, 5, 6], 3))
219 [[1, 2, 3], [4, 5, 6]]
221 By the default, the last yielded list will have fewer than *n* elements
222 if the length of *iterable* is not divisible by *n*:
224 >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
225 [[1, 2, 3], [4, 5, 6], [7, 8]]
227 To use a fill-in value instead, see the :func:`grouper` recipe.
229 If the length of *iterable* is not divisible by *n* and *strict* is
230 ``True``, then ``ValueError`` will be raised before the last
231 list is yielded.
233 """
234 if n is not None and n < 0:
235 raise ValueError('n must be at least 0')
237 iterator = iter(partial(take, n, iter(iterable)), [])
238 if strict:
239 if n is None:
240 raise ValueError('n must not be None when using strict mode.')
242 def ret():
243 for chunk in iterator:
244 if len(chunk) != n:
245 raise ValueError('iterable is not divisible by n.')
246 yield chunk
248 return ret()
249 else:
250 return iterator
253def first(iterable, default=_marker):
254 """Return the first item of *iterable*, or *default* if *iterable* is
255 empty.
257 >>> first([0, 1, 2, 3])
258 0
259 >>> first([], 'some default')
260 'some default'
262 If *default* is not provided and there are no items in the iterable,
263 raise ``ValueError``.
265 :func:`first` is useful when you have a generator of expensive-to-retrieve
266 values and want any arbitrary one. It is marginally shorter than
267 ``next(iter(iterable), default)``.
269 """
270 for item in iterable:
271 return item
272 if default is _marker:
273 raise ValueError(
274 'first() was called on an empty iterable, '
275 'and no default value was provided.'
276 )
277 return default
280def last(iterable, default=_marker):
281 """Return the last item of *iterable*, or *default* if *iterable* is
282 empty.
284 >>> last([0, 1, 2, 3])
285 3
286 >>> last([], 'some default')
287 'some default'
289 If *default* is not provided and there are no items in the iterable,
290 raise ``ValueError``.
291 """
292 try:
293 if getattr(iterable, '__reversed__', None):
294 return next(reversed(iterable))
295 return deque(iterable, maxlen=1)[-1]
296 except (IndexError, StopIteration):
297 if default is _marker:
298 raise ValueError(
299 'last() was called on an empty iterable, '
300 'and no default value was provided.'
301 )
302 return default
305def nth_or_last(iterable, n, default=_marker):
306 """Return the nth or the last item of *iterable*,
307 or *default* if *iterable* is empty.
309 >>> nth_or_last([0, 1, 2, 3], 2)
310 2
311 >>> nth_or_last([0, 1], 2)
312 1
313 >>> nth_or_last([], 0, 'some default')
314 'some default'
316 If *default* is not provided and there are no items in the iterable,
317 raise ``ValueError``.
318 """
319 return last(islice(iterable, n + 1), default=default)
322class peekable:
323 """Wrap an iterator to allow lookahead and prepending elements.
325 Call :meth:`peek` on the result to get the value that will be returned
326 by :func:`next`. This won't advance the iterator:
328 >>> p = peekable(['a', 'b'])
329 >>> p.peek()
330 'a'
331 >>> next(p)
332 'a'
334 Pass :meth:`peek` a default value to return that instead of raising
335 ``StopIteration`` when the iterator is exhausted.
337 >>> p = peekable([])
338 >>> p.peek('hi')
339 'hi'
341 peekables also offer a :meth:`prepend` method, which "inserts" items
342 at the head of the iterable:
344 >>> p = peekable([1, 2, 3])
345 >>> p.prepend(10, 11, 12)
346 >>> next(p)
347 10
348 >>> p.peek()
349 11
350 >>> list(p)
351 [11, 12, 1, 2, 3]
353 peekables can be indexed. Index 0 is the item that will be returned by
354 :func:`next`, index 1 is the item after that, and so on:
355 The values up to the given index will be cached.
357 >>> p = peekable(['a', 'b', 'c', 'd'])
358 >>> p[0]
359 'a'
360 >>> p[1]
361 'b'
362 >>> next(p)
363 'a'
365 Negative indexes are supported, but be aware that they will cache the
366 remaining items in the source iterator, which may require significant
367 storage.
369 To check whether a peekable is exhausted, check its truth value:
371 >>> p = peekable(['a', 'b'])
372 >>> if p: # peekable has items
373 ... list(p)
374 ['a', 'b']
375 >>> if not p: # peekable is exhausted
376 ... list(p)
377 []
379 """
381 def __init__(self, iterable):
382 self._it = iter(iterable)
383 self._cache = deque()
385 def __iter__(self):
386 return self
388 def __bool__(self):
389 try:
390 self.peek()
391 except StopIteration:
392 return False
393 return True
395 def peek(self, default=_marker):
396 """Return the item that will be next returned from ``next()``.
398 Return ``default`` if there are no items left. If ``default`` is not
399 provided, raise ``StopIteration``.
401 """
402 if not self._cache:
403 try:
404 self._cache.append(next(self._it))
405 except StopIteration:
406 if default is _marker:
407 raise
408 return default
409 return self._cache[0]
411 def prepend(self, *items):
412 """Stack up items to be the next ones returned from ``next()`` or
413 ``self.peek()``. The items will be returned in
414 first in, first out order::
416 >>> p = peekable([1, 2, 3])
417 >>> p.prepend(10, 11, 12)
418 >>> next(p)
419 10
420 >>> list(p)
421 [11, 12, 1, 2, 3]
423 It is possible, by prepending items, to "resurrect" a peekable that
424 previously raised ``StopIteration``.
426 >>> p = peekable([])
427 >>> next(p)
428 Traceback (most recent call last):
429 ...
430 StopIteration
431 >>> p.prepend(1)
432 >>> next(p)
433 1
434 >>> next(p)
435 Traceback (most recent call last):
436 ...
437 StopIteration
439 """
440 self._cache.extendleft(reversed(items))
442 __class_getitem__ = classmethod(types.GenericAlias)
444 def __next__(self):
445 if self._cache:
446 return self._cache.popleft()
448 return next(self._it)
450 def _get_slice(self, index):
451 # Normalize the slice's arguments
452 step = 1 if (index.step is None) else index.step
453 if step > 0:
454 start = 0 if (index.start is None) else index.start
455 stop = maxsize if (index.stop is None) else index.stop
456 elif step < 0:
457 start = -1 if (index.start is None) else index.start
458 stop = (-maxsize - 1) if (index.stop is None) else index.stop
459 else:
460 raise ValueError('slice step cannot be zero')
462 # If either the start or stop index is negative, we'll need to cache
463 # the rest of the iterable in order to slice from the right side.
464 if (start < 0) or (stop < 0):
465 self._cache.extend(self._it)
466 # Otherwise we'll need to find the rightmost index and cache to that
467 # point.
468 else:
469 n = min(max(start, stop) + 1, maxsize)
470 cache_len = len(self._cache)
471 if n >= cache_len:
472 self._cache.extend(islice(self._it, n - cache_len))
474 return list(self._cache)[index]
476 def __getitem__(self, index):
477 if isinstance(index, slice):
478 return self._get_slice(index)
480 cache_len = len(self._cache)
481 if index < 0:
482 self._cache.extend(self._it)
483 elif index >= cache_len:
484 self._cache.extend(islice(self._it, index + 1 - cache_len))
486 return self._cache[index]
489def consumer(func):
490 """Decorator that automatically advances a PEP-342-style "reverse iterator"
491 to its first yield point so you don't have to call ``next()`` on it
492 manually.
494 >>> @consumer
495 ... def tally():
496 ... i = 0
497 ... while True:
498 ... print('Thing number %s is %s.' % (i, (yield)))
499 ... i += 1
500 ...
501 >>> t = tally()
502 >>> t.send('red')
503 Thing number 0 is red.
504 >>> t.send('fish')
505 Thing number 1 is fish.
507 Without the decorator, you would have to call ``next(t)`` before
508 ``t.send()`` could be used.
510 """
512 @wraps(func)
513 def wrapper(*args, **kwargs):
514 gen = func(*args, **kwargs)
515 next(gen)
516 return gen
518 return wrapper
521def ilen(iterable):
522 """Return the number of items in *iterable*.
524 For example, there are 168 prime numbers below 1,000:
526 >>> ilen(sieve(1000))
527 168
529 Equivalent to, but faster than::
531 def ilen(iterable):
532 count = 0
533 for _ in iterable:
534 count += 1
535 return count
537 This fully consumes the iterable, so handle with care.
539 """
540 # This is the "most beautiful of the fast variants" of this function.
541 # If you think you can improve on it, please ensure that your version
542 # is both 10x faster and 10x more beautiful.
543 return sum(compress(repeat(1), zip(iterable)))
546def iterate(func, start):
547 """Return ``start``, ``func(start)``, ``func(func(start))``, ...
549 Produces an infinite iterator. To add a stopping condition,
550 use :func:`take`, ``takewhile``, or :func:`takewhile_inclusive`:.
552 >>> take(10, iterate(lambda x: 2*x, 1))
553 [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
555 >>> collatz = lambda x: 3*x + 1 if x%2==1 else x // 2
556 >>> list(takewhile_inclusive(lambda x: x!=1, iterate(collatz, 10)))
557 [10, 5, 16, 8, 4, 2, 1]
559 """
560 with suppress(StopIteration):
561 while True:
562 yield start
563 start = func(start)
566def with_iter(context_manager):
567 """Wrap an iterable in a ``with`` statement, so it closes once exhausted.
569 For example, this will close the file when the iterator is exhausted::
571 upper_lines = (line.upper() for line in with_iter(open('foo')))
573 Note that you have to actually exhaust the iterator for opened files to be closed.
575 Any context manager which returns an iterable is a candidate for
576 ``with_iter``.
578 """
579 with context_manager as iterable:
580 yield from iterable
583class sized_iterator:
584 """Wrapper for *iterable* that implements ``__len__``.
586 >>> it = map(str, range(5))
587 >>> sized_it = sized_iterator(it, 5)
588 >>> len(sized_it)
589 5
590 >>> list(sized_it)
591 ['0', '1', '2', '3', '4']
593 This is useful for tools that use :func:`len`, like
594 `tqdm <https://pypi.org/project/tqdm/>`__ .
596 The wrapper doesn't validate the provided *length*, so be sure to choose
597 a value that reflects reality.
598 """
600 def __init__(self, iterable, length):
601 self._iterator = iter(iterable)
602 self._length = length
604 def __next__(self):
605 return next(self._iterator)
607 def __iter__(self):
608 return self
610 def __len__(self):
611 return self._length
614def one(iterable, too_short=None, too_long=None):
615 """Return the first item from *iterable*, which is expected to contain only
616 that item. Raise an exception if *iterable* is empty or has more than one
617 item.
619 :func:`one` is useful for ensuring that an iterable contains only one item.
620 For example, it can be used to retrieve the result of a database query
621 that is expected to return a single row.
623 If *iterable* is empty, ``ValueError`` will be raised. You may specify a
624 different exception with the *too_short* keyword:
626 >>> it = []
627 >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
628 Traceback (most recent call last):
629 ...
630 ValueError: too few items in iterable (expected 1)'
631 >>> too_short = IndexError('too few items')
632 >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL
633 Traceback (most recent call last):
634 ...
635 IndexError: too few items
637 Similarly, if *iterable* contains more than one item, ``ValueError`` will
638 be raised. You may specify a different exception with the *too_long*
639 keyword:
641 >>> it = ['too', 'many']
642 >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
643 Traceback (most recent call last):
644 ...
645 ValueError: Expected exactly one item in iterable, but got 'too',
646 'many', and perhaps more.
647 >>> too_long = RuntimeError
648 >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL
649 Traceback (most recent call last):
650 ...
651 RuntimeError
653 Note that :func:`one` attempts to advance *iterable* twice to ensure there
654 is only one item. See :func:`spy` or :func:`peekable` to check iterable
655 contents less destructively.
657 """
658 iterator = iter(iterable)
659 for first in iterator:
660 for second in iterator:
661 if too_long is not None:
662 raise too_long
663 raise ValueError(
664 f'Expected exactly one item in iterable, but got {first!r}, '
665 f'{second!r}, and perhaps more.'
666 )
667 return first
668 if too_short is not None:
669 raise too_short
670 raise ValueError('too few items in iterable (expected 1)')
673def raise_(exception, *args):
674 raise exception(*args)
677def strictly_n(iterable, n, too_short=None, too_long=None):
678 """Validate that *iterable* has exactly *n* items and return them if
679 it does. If it has fewer than *n* items, call function *too_short*
680 with the actual number of items. If it has more than *n* items, call function
681 *too_long* with the number ``n + 1``.
683 >>> iterable = ['a', 'b', 'c', 'd']
684 >>> n = 4
685 >>> list(strictly_n(iterable, n))
686 ['a', 'b', 'c', 'd']
688 Note that the returned iterable must be consumed in order for the check to
689 be made.
691 By default, *too_short* and *too_long* are functions that raise
692 ``ValueError``.
694 >>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL
695 Traceback (most recent call last):
696 ...
697 ValueError: too few items in iterable (got 2)
699 >>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL
700 Traceback (most recent call last):
701 ...
702 ValueError: too many items in iterable (got at least 3)
704 You can instead supply functions that do something else.
705 *too_short* will be called with the number of items in *iterable*.
706 *too_long* will be called with `n + 1`.
708 >>> def too_short(item_count):
709 ... raise RuntimeError
710 >>> it = strictly_n('abcd', 6, too_short=too_short)
711 >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL
712 Traceback (most recent call last):
713 ...
714 RuntimeError
716 >>> def too_long(item_count):
717 ... print('The boss is going to hear about this')
718 >>> it = strictly_n('abcdef', 4, too_long=too_long)
719 >>> list(it)
720 The boss is going to hear about this
721 ['a', 'b', 'c', 'd']
723 """
724 if too_short is None:
725 too_short = lambda item_count: raise_(
726 ValueError,
727 f'Too few items in iterable (got {item_count})',
728 )
730 if too_long is None:
731 too_long = lambda item_count: raise_(
732 ValueError,
733 f'Too many items in iterable (got at least {item_count})',
734 )
736 it = iter(iterable)
738 sent = 0
739 for item in islice(it, n):
740 yield item
741 sent += 1
743 if sent < n:
744 too_short(sent)
745 return
747 for item in it:
748 too_long(n + 1)
749 return
752def distinct_permutations(iterable, r=None):
753 """Yield successive distinct permutations of the elements in *iterable*.
755 >>> sorted(distinct_permutations([1, 0, 1]))
756 [(0, 1, 1), (1, 0, 1), (1, 1, 0)]
758 Equivalent to yielding from ``set(permutations(iterable))``, except
759 duplicates are not generated and thrown away. For larger input sequences
760 this is much more efficient.
762 If the elements of the input iterable are sortable, the output tuples are
763 produced in sorted order.
765 Duplicate permutations arise when there are duplicated elements in the
766 input iterable. The number of items returned is
767 `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of
768 items input, and each `x_i` is the count of a distinct item in the input
769 sequence. The function :func:`multinomial` computes this directly.
771 If *r* is given, only the *r*-length permutations are yielded.
773 >>> sorted(distinct_permutations([1, 0, 1], r=2))
774 [(0, 1), (1, 0), (1, 1)]
775 >>> sorted(distinct_permutations(range(3), r=2))
776 [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
778 *iterable* need not be sortable, but note that using equal (``x == y``)
779 but non-identical (``id(x) != id(y)``) elements may produce surprising
780 behavior. For example, ``1`` and ``True`` are equal but non-identical:
782 >>> list(distinct_permutations([1, True, '3'])) # doctest: +SKIP
783 [
784 (1, True, '3'),
785 (1, '3', True),
786 ('3', 1, True)
787 ]
788 >>> list(distinct_permutations([1, 2, '3'])) # doctest: +SKIP
789 [
790 (1, 2, '3'),
791 (1, '3', 2),
792 (2, 1, '3'),
793 (2, '3', 1),
794 ('3', 1, 2),
795 ('3', 2, 1)
796 ]
797 """
799 # Algorithm: https://w.wiki/Qai
800 def _full(A):
801 while True:
802 # Yield the permutation we have
803 yield tuple(A)
805 # Find the largest index i such that A[i] < A[i + 1]
806 for i in range(size - 2, -1, -1):
807 if A[i] < A[i + 1]:
808 break
809 # If no such index exists, this permutation is the last one
810 else:
811 return
813 # Find the largest index j greater than j such that A[i] < A[j]
814 for j in range(size - 1, i, -1):
815 if A[i] < A[j]:
816 break
818 # Swap the value of A[i] with that of A[j], then reverse the
819 # sequence from A[i + 1] to form the new permutation
820 A[i], A[j] = A[j], A[i]
821 A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1]
823 # Algorithm: modified from the above
824 def _partial(A, r):
825 # Split A into the first r items and the last r items
826 head, tail = A[:r], A[r:]
827 right_head_indexes = range(r - 1, -1, -1)
828 left_tail_indexes = range(len(tail))
830 while True:
831 # Yield the permutation we have
832 yield tuple(head)
834 # Starting from the right, find the first index of the head with
835 # value smaller than the maximum value of the tail - call it i.
836 pivot = tail[-1]
837 for i in right_head_indexes:
838 if head[i] < pivot:
839 break
840 pivot = head[i]
841 else:
842 return
844 # Starting from the left, find the first value of the tail
845 # with a value greater than head[i] and swap.
846 for j in left_tail_indexes:
847 if tail[j] > head[i]:
848 head[i], tail[j] = tail[j], head[i]
849 break
850 # If we didn't find one, start from the right and find the first
851 # index of the head with a value greater than head[i] and swap.
852 else:
853 for j in right_head_indexes:
854 if head[j] > head[i]:
855 head[i], head[j] = head[j], head[i]
856 break
858 # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)]
859 tail += head[: i - r : -1] # head[i + 1:][::-1]
860 i += 1
861 head[i:], tail[:] = tail[: r - i], tail[r - i :]
863 items = list(iterable)
865 try:
866 items.sort()
867 sortable = True
868 except TypeError:
869 sortable = False
871 indices_dict = defaultdict(list)
873 for item in items:
874 indices_dict[items.index(item)].append(item)
876 indices = [items.index(item) for item in items]
877 indices.sort()
879 equivalent_items = {k: cycle(v) for k, v in indices_dict.items()}
881 def permuted_items(permuted_indices):
882 return tuple(
883 next(equivalent_items[index]) for index in permuted_indices
884 )
886 size = len(items)
887 if r is None:
888 r = size
890 # functools.partial(_partial, ... )
891 algorithm = _full if (r == size) else partial(_partial, r=r)
893 if 0 < r <= size:
894 if sortable:
895 return algorithm(items)
896 else:
897 return (
898 permuted_items(permuted_indices)
899 for permuted_indices in algorithm(indices)
900 )
902 return iter(() if r else ((),))
905def derangements(iterable, r=None):
906 """Yield successive derangements of the elements in *iterable*.
908 A derangement is a permutation in which no element appears at its original
909 index. In other words, a derangement is a permutation that has no fixed points.
911 Suppose Alice, Bob, Carol, and Dave are playing Secret Santa.
912 The code below outputs all of the different ways to assign gift recipients
913 such that nobody is assigned to himself or herself:
915 >>> for d in derangements(['Alice', 'Bob', 'Carol', 'Dave']):
916 ... print(', '.join(d))
917 Bob, Alice, Dave, Carol
918 Bob, Carol, Dave, Alice
919 Bob, Dave, Alice, Carol
920 Carol, Alice, Dave, Bob
921 Carol, Dave, Alice, Bob
922 Carol, Dave, Bob, Alice
923 Dave, Alice, Bob, Carol
924 Dave, Carol, Alice, Bob
925 Dave, Carol, Bob, Alice
927 If *r* is given, only the *r*-length derangements are yielded.
929 >>> sorted(derangements(range(3), 2))
930 [(1, 0), (1, 2), (2, 0)]
931 >>> sorted(derangements([0, 2, 3], 2))
932 [(2, 0), (2, 3), (3, 0)]
934 Elements are treated as unique based on their position, not on their value.
936 Consider the Secret Santa example with two *different* people who have
937 the *same* name. Then there are two valid gift assignments even though
938 it might appear that a person is assigned to themselves:
940 >>> names = ['Alice', 'Bob', 'Bob']
941 >>> list(derangements(names))
942 [('Bob', 'Bob', 'Alice'), ('Bob', 'Alice', 'Bob')]
944 To avoid confusion, make the inputs distinct:
946 >>> deduped = [f'{name}{index}' for index, name in enumerate(names)]
947 >>> list(derangements(deduped))
948 [('Bob1', 'Bob2', 'Alice0'), ('Bob2', 'Alice0', 'Bob1')]
950 The number of derangements of a set of size *n* is known as the
951 "subfactorial of n". For n > 0, the subfactorial is:
952 ``round(math.factorial(n) / math.e)``. The more-itertools function
953 :func:`subfactorial` computes this directly.
955 References:
957 * Article: https://www.numberanalytics.com/blog/ultimate-guide-to-derangements-in-combinatorics
958 * Sizes: https://oeis.org/A000166
959 """
960 xs = tuple(iterable)
961 ys = tuple(range(len(xs)))
962 return compress(
963 permutations(xs, r=r),
964 map(all, map(map, repeat(is_not), repeat(ys), permutations(ys, r=r))),
965 )
968def intersperse(e, iterable, n=1):
969 """Intersperse filler element *e* among the items in *iterable*, leaving
970 *n* items between each filler element.
972 >>> list(intersperse('!', [1, 2, 3, 4, 5]))
973 [1, '!', 2, '!', 3, '!', 4, '!', 5]
975 >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))
976 [1, 2, None, 3, 4, None, 5]
978 """
979 if n == 0:
980 raise ValueError('n must be > 0')
981 elif n == 1:
982 # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2...
983 # islice(..., 1, None) -> x_0, e, x_1, e, x_2...
984 return islice(interleave(repeat(e), iterable), 1, None)
985 else:
986 # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...
987 # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]...
988 # flatten(...) -> x_0, x_1, e, x_2, x_3...
989 filler = repeat([e])
990 chunks = chunked(iterable, n)
991 return flatten(islice(interleave(filler, chunks), 1, None))
994def unique_to_each(*iterables):
995 """Return the elements from each of the input iterables that aren't in the
996 other input iterables.
998 For example, suppose you have a set of packages, each with a set of
999 dependencies::
1001 {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}
1003 If you remove one package, which dependencies can also be removed?
1005 If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not
1006 associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for
1007 ``pkg_2``, and ``D`` is only needed for ``pkg_3``::
1009 >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})
1010 [['A'], ['C'], ['D']]
1012 If there are duplicates in one input iterable that aren't in the others
1013 they will be duplicated in the output. Input order is preserved::
1015 >>> unique_to_each("mississippi", "missouri")
1016 [['p', 'p'], ['o', 'u', 'r']]
1018 It is assumed that the elements of each iterable are hashable.
1020 """
1021 pool = [list(it) for it in iterables]
1022 counts = Counter(chain.from_iterable(map(set, pool)))
1023 uniques = {element for element in counts if counts[element] == 1}
1024 return [list(filter(uniques.__contains__, it)) for it in pool]
1027def windowed(seq, n, fillvalue=None, step=1):
1028 """Return a sliding window of width *n* over the given iterable.
1030 >>> all_windows = windowed([1, 2, 3, 4, 5], 3)
1031 >>> list(all_windows)
1032 [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
1034 When the window is larger than the iterable, *fillvalue* is used in place
1035 of missing values:
1037 >>> list(windowed([1, 2, 3], 4))
1038 [(1, 2, 3, None)]
1040 Each window will advance in increments of *step*:
1042 >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))
1043 [(1, 2, 3), (3, 4, 5), (5, 6, '!')]
1045 To slide into the iterable's items, use :func:`chain` to add filler items
1046 to the left:
1048 >>> iterable = [1, 2, 3, 4]
1049 >>> n = 3
1050 >>> padding = [None] * (n - 1)
1051 >>> list(windowed(chain(padding, iterable), 3))
1052 [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]
1053 """
1054 if n <= 0:
1055 raise ValueError('n must be > 0')
1056 if step < 1:
1057 raise ValueError('step must be >= 1')
1059 iterator = iter(seq)
1061 # Generate first window
1062 window = deque(islice(iterator, n), maxlen=n)
1064 # Deal with the first window not being full
1065 if not window:
1066 return
1067 if len(window) < n:
1068 yield tuple(window) + ((fillvalue,) * (n - len(window)))
1069 return
1070 yield tuple(window)
1072 # Create the filler for the next windows. The padding ensures
1073 # we have just enough elements to fill the last window.
1074 padding = (fillvalue,) * (n - 1 if step >= n else step - 1)
1075 filler = map(window.append, chain(iterator, padding))
1077 # Generate the rest of the windows
1078 for _ in islice(filler, step - 1, None, step):
1079 yield tuple(window)
1082def substrings(iterable):
1083 """Yield all of the substrings of *iterable*.
1085 >>> [''.join(s) for s in substrings('more')]
1086 ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']
1088 Note that non-string iterables can also be subdivided.
1090 >>> list(substrings([0, 1, 2]))
1091 [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
1093 Like subslices() but returns tuples instead of lists
1094 and returns the shortest substrings first.
1096 """
1097 seq = tuple(iterable)
1098 item_count = len(seq)
1099 for n in range(1, item_count + 1):
1100 slices = map(slice, range(item_count), range(n, item_count + 1))
1101 yield from map(getitem, repeat(seq), slices)
1104def substrings_indexes(seq, reverse=False):
1105 """Yield all substrings and their positions in *seq*
1107 The items yielded will be a tuple of the form ``(substr, i, j)``, where
1108 ``substr == seq[i:j]``.
1110 This function only works for iterables that support slicing, such as
1111 ``str`` objects.
1113 >>> for item in substrings_indexes('more'):
1114 ... print(item)
1115 ('m', 0, 1)
1116 ('o', 1, 2)
1117 ('r', 2, 3)
1118 ('e', 3, 4)
1119 ('mo', 0, 2)
1120 ('or', 1, 3)
1121 ('re', 2, 4)
1122 ('mor', 0, 3)
1123 ('ore', 1, 4)
1124 ('more', 0, 4)
1126 Set *reverse* to ``True`` to yield the same items in the opposite order.
1129 """
1130 r = range(1, len(seq) + 1)
1131 if reverse:
1132 r = reversed(r)
1133 return (
1134 (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)
1135 )
1138class bucket:
1139 """Wrap *iterable* and return an object that buckets the iterable into
1140 child iterables based on a *key* function.
1142 >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
1143 >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character
1144 >>> sorted(list(s)) # Get the keys
1145 ['a', 'b', 'c']
1146 >>> a_iterable = s['a']
1147 >>> next(a_iterable)
1148 'a1'
1149 >>> next(a_iterable)
1150 'a2'
1151 >>> list(s['b'])
1152 ['b1', 'b2', 'b3']
1154 The original iterable will be advanced and its items will be cached until
1155 they are used by the child iterables. This may require significant storage.
1157 By default, attempting to select a bucket to which no items belong will
1158 exhaust the iterable and cache all values.
1159 If you specify a *validator* function, selected buckets will instead be
1160 checked against it.
1162 >>> from itertools import count
1163 >>> it = count(1, 2) # Infinite sequence of odd numbers
1164 >>> key = lambda x: x % 10 # Bucket by last digit
1165 >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only
1166 >>> s = bucket(it, key=key, validator=validator)
1167 >>> 2 in s
1168 False
1169 >>> list(s[2])
1170 []
1172 .. seealso:: :func:`map_reduce`, :func:`groupby_transform`
1174 If storage is not a concern, :func:`map_reduce` returns a Python
1175 dictionary, which is generally easier to work with. If the elements
1176 with the same key are already adjacent, :func:`groupby_transform`
1177 or :func:`itertools.groupby` can be used without any caching overhead.
1179 """
1181 def __init__(self, iterable, key, validator=None):
1182 self._it = iter(iterable)
1183 self._key = key
1184 self._cache = defaultdict(deque)
1185 self._validator = validator or (lambda x: True)
1187 def __contains__(self, value):
1188 if not self._validator(value):
1189 return False
1191 try:
1192 item = next(self[value])
1193 except StopIteration:
1194 return False
1195 else:
1196 self._cache[value].appendleft(item)
1198 return True
1200 def _get_values(self, value):
1201 """
1202 Helper to yield items from the parent iterator that match *value*.
1203 Items that don't match are stored in the local cache as they
1204 are encountered.
1205 """
1206 while True:
1207 # If we've cached some items that match the target value, emit
1208 # the first one and evict it from the cache.
1209 if self._cache.get(value):
1210 yield self._cache[value].popleft()
1211 # Otherwise we need to advance the parent iterator to search for
1212 # a matching item, caching the rest.
1213 else:
1214 while True:
1215 try:
1216 item = next(self._it)
1217 except StopIteration:
1218 return
1219 item_value = self._key(item)
1220 if item_value == value:
1221 if value not in self._cache:
1222 self._cache[value] = deque()
1223 yield item
1224 break
1225 elif self._validator(item_value):
1226 self._cache[item_value].append(item)
1228 def __iter__(self):
1229 for item in self._it:
1230 item_value = self._key(item)
1231 if self._validator(item_value):
1232 self._cache[item_value].append(item)
1234 return iter(self._cache)
1236 def __getitem__(self, value):
1237 if not self._validator(value):
1238 return iter(())
1240 return self._get_values(value)
1243def spy(iterable, n=1):
1244 """Return a 2-tuple with a list containing the first *n* elements of
1245 *iterable*, and an iterator with the same items as *iterable*.
1246 This allows you to "look ahead" at the items in the iterable without
1247 advancing it.
1249 There is one item in the list by default:
1251 >>> iterable = 'abcdefg'
1252 >>> head, iterable = spy(iterable)
1253 >>> head
1254 ['a']
1255 >>> list(iterable)
1256 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
1258 You may use unpacking to retrieve items instead of lists:
1260 >>> (head,), iterable = spy('abcdefg')
1261 >>> head
1262 'a'
1263 >>> (first, second), iterable = spy('abcdefg', 2)
1264 >>> first
1265 'a'
1266 >>> second
1267 'b'
1269 The number of items requested can be larger than the number of items in
1270 the iterable:
1272 >>> iterable = [1, 2, 3, 4, 5]
1273 >>> head, iterable = spy(iterable, 10)
1274 >>> head
1275 [1, 2, 3, 4, 5]
1276 >>> list(iterable)
1277 [1, 2, 3, 4, 5]
1279 """
1280 p, q = tee(iterable)
1281 return take(n, q), p
1284def interleave(*iterables):
1285 """Return a new iterable yielding from each iterable in turn,
1286 until the shortest is exhausted.
1288 >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))
1289 [1, 4, 6, 2, 5, 7]
1291 For a version that doesn't terminate after the shortest iterable is
1292 exhausted, see :func:`interleave_longest`.
1294 """
1295 return chain.from_iterable(zip(*iterables))
1298def interleave_longest(*iterables):
1299 """Return a new iterable yielding from each iterable in turn,
1300 skipping any that are exhausted.
1302 >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))
1303 [1, 4, 6, 2, 5, 7, 3, 8]
1305 This function produces the same output as :func:`roundrobin`, but may
1306 perform better for some inputs (in particular when the number of iterables
1307 is large).
1309 """
1310 for xs in zip_longest(*iterables, fillvalue=_marker):
1311 for x in xs:
1312 if x is not _marker:
1313 yield x
1316def interleave_evenly(iterables, lengths=None):
1317 """
1318 Interleave multiple iterables so that their elements are evenly distributed
1319 throughout the output sequence.
1321 >>> iterables = [1, 2, 3, 4, 5], ['a', 'b']
1322 >>> list(interleave_evenly(iterables))
1323 [1, 2, 'a', 3, 4, 'b', 5]
1325 >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]]
1326 >>> list(interleave_evenly(iterables))
1327 [1, 6, 4, 2, 7, 3, 8, 5]
1329 This function requires iterables of known length. Iterables without
1330 ``__len__()`` can be used by manually specifying lengths with *lengths*:
1332 >>> from itertools import combinations, repeat
1333 >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']]
1334 >>> lengths = [4 * (4 - 1) // 2, 3]
1335 >>> list(interleave_evenly(iterables, lengths=lengths))
1336 [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c']
1338 Based on Bresenham's algorithm.
1339 """
1340 if lengths is None:
1341 try:
1342 lengths = [len(it) for it in iterables]
1343 except TypeError:
1344 raise ValueError(
1345 'Iterable lengths could not be determined automatically. '
1346 'Specify them with the lengths keyword.'
1347 )
1348 elif len(iterables) != len(lengths):
1349 raise ValueError('Mismatching number of iterables and lengths.')
1351 dims = len(lengths)
1353 if not dims:
1354 return
1356 # sort iterables by length, descending
1357 lengths_permute = sorted(
1358 range(dims), key=lambda i: lengths[i], reverse=True
1359 )
1360 lengths_desc = [lengths[i] for i in lengths_permute]
1361 iters_desc = [iter(iterables[i]) for i in lengths_permute]
1363 # the longest iterable is the primary one (Bresenham: the longest
1364 # distance along an axis)
1365 delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:]
1366 iter_primary, iters_secondary = iters_desc[0], iters_desc[1:]
1367 errors = [delta_primary // dims] * len(deltas_secondary)
1369 to_yield = sum(lengths)
1370 while to_yield:
1371 yield next(iter_primary)
1372 to_yield -= 1
1373 # update errors for each secondary iterable
1374 errors = [e - delta for e, delta in zip(errors, deltas_secondary)]
1376 # those iterables for which the error is negative are yielded
1377 # ("diagonal step" in Bresenham)
1378 for i, e_ in enumerate(errors):
1379 if e_ < 0:
1380 yield next(iters_secondary[i])
1381 to_yield -= 1
1382 errors[i] += delta_primary
1385def interleave_randomly(*iterables):
1386 """Repeatedly select one of the input *iterables* at random and yield the next
1387 item from it.
1389 >>> iterables = [1, 2, 3], 'abc', (True, False, None)
1390 >>> list(interleave_randomly(*iterables)) # doctest: +SKIP
1391 ['a', 'b', 1, 'c', True, False, None, 2, 3]
1393 The relative order of the items in each input iterable will preserved. Note the
1394 sequences of items with this property are not equally likely to be generated.
1396 """
1397 iterators = [iter(e) for e in iterables]
1398 while iterators:
1399 idx = randrange(len(iterators))
1400 try:
1401 yield next(iterators[idx])
1402 except StopIteration:
1403 # equivalent to `list.pop` but slightly faster
1404 iterators[idx] = iterators[-1]
1405 del iterators[-1]
1408def collapse(iterable, base_type=None, levels=None):
1409 """Flatten an iterable with multiple levels of nesting (e.g., a list of
1410 lists of tuples) into non-iterable types.
1412 >>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
1413 >>> list(collapse(iterable))
1414 [1, 2, 3, 4, 5, 6]
1416 Binary and text strings are not considered iterable and
1417 will not be collapsed.
1419 To avoid collapsing other types, specify *base_type*:
1421 >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
1422 >>> list(collapse(iterable, base_type=tuple))
1423 ['ab', ('cd', 'ef'), 'gh', 'ij']
1425 Specify *levels* to stop flattening after a certain level:
1427 >>> iterable = [('a', ['b']), ('c', ['d'])]
1428 >>> list(collapse(iterable)) # Fully flattened
1429 ['a', 'b', 'c', 'd']
1430 >>> list(collapse(iterable, levels=1)) # Only one level flattened
1431 ['a', ['b'], 'c', ['d']]
1433 """
1434 stack = deque()
1435 # Add our first node group, treat the iterable as a single node
1436 stack.appendleft((0, repeat(iterable, 1)))
1438 while stack:
1439 node_group = stack.popleft()
1440 level, nodes = node_group
1442 # Check if beyond max level
1443 if levels is not None and level > levels:
1444 yield from nodes
1445 continue
1447 for node in nodes:
1448 # Check if done iterating
1449 if isinstance(node, (str, bytes)) or (
1450 (base_type is not None) and isinstance(node, base_type)
1451 ):
1452 yield node
1453 # Otherwise try to create child nodes
1454 else:
1455 try:
1456 tree = iter(node)
1457 except TypeError:
1458 yield node
1459 else:
1460 # Save our current location
1461 stack.appendleft(node_group)
1462 # Append the new child node
1463 stack.appendleft((level + 1, tree))
1464 # Break to process child node
1465 break
1468def side_effect(func, iterable, chunk_size=None, before=None, after=None):
1469 """Invoke *func* on each item in *iterable* (or on each *chunk_size* group
1470 of items) before yielding the item.
1472 `func` must be a function that takes a single argument. Its return value
1473 will be discarded.
1475 *before* and *after* are optional functions that take no arguments. They
1476 will be executed before iteration starts and after it ends, respectively.
1478 `side_effect` can be used for logging, updating progress bars, or anything
1479 that is not functionally "pure."
1481 Emitting a status message:
1483 >>> from more_itertools import consume
1484 >>> func = lambda item: print('Received {}'.format(item))
1485 >>> consume(side_effect(func, range(2)))
1486 Received 0
1487 Received 1
1489 Operating on chunks of items:
1491 >>> pair_sums = []
1492 >>> func = lambda chunk: pair_sums.append(sum(chunk))
1493 >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2))
1494 [0, 1, 2, 3, 4, 5]
1495 >>> list(pair_sums)
1496 [1, 5, 9]
1498 Writing to a file-like object:
1500 >>> from io import StringIO
1501 >>> from more_itertools import consume
1502 >>> f = StringIO()
1503 >>> func = lambda x: print(x, file=f)
1504 >>> before = lambda: print('HEADER', file=f)
1505 >>> after = f.close
1506 >>> it = ['a', 'b', 'c']
1507 >>> consume(side_effect(func, it, before=before, after=after))
1508 >>> f.closed
1509 True
1511 """
1512 try:
1513 if before is not None:
1514 before()
1516 if chunk_size is None:
1517 for item in iterable:
1518 func(item)
1519 yield item
1520 else:
1521 for chunk in chunked(iterable, chunk_size):
1522 func(chunk)
1523 yield from chunk
1524 finally:
1525 if after is not None:
1526 after()
1529def sliced(seq, n, strict=False):
1530 """Yield slices of length *n* from the sequence *seq*.
1532 >>> list(sliced((1, 2, 3, 4, 5, 6), 3))
1533 [(1, 2, 3), (4, 5, 6)]
1535 By the default, the last yielded slice will have fewer than *n* elements
1536 if the length of *seq* is not divisible by *n*:
1538 >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))
1539 [(1, 2, 3), (4, 5, 6), (7, 8)]
1541 If the length of *seq* is not divisible by *n* and *strict* is
1542 ``True``, then ``ValueError`` will be raised before the last
1543 slice is yielded.
1545 This function will only work for iterables that support slicing.
1546 For non-sliceable iterables, see :func:`chunked`.
1548 """
1549 if n < 0:
1550 raise ValueError('n must be at least 0')
1552 iterator = takewhile(len, (seq[i : i + n] for i in count(0, n)))
1553 if strict:
1555 def ret():
1556 for _slice in iterator:
1557 if len(_slice) != n:
1558 raise ValueError("seq is not divisible by n.")
1559 yield _slice
1561 return ret()
1562 else:
1563 return iterator
1566def split_at(iterable, pred, maxsplit=-1, keep_separator=False):
1567 """Yield lists of items from *iterable*, where each list is delimited by
1568 an item where callable *pred* returns ``True``.
1570 >>> list(split_at('abcdcba', lambda x: x == 'b'))
1571 [['a'], ['c', 'd', 'c'], ['a']]
1573 >>> list(split_at(range(10), lambda n: n % 2 == 1))
1574 [[0], [2], [4], [6], [8], []]
1576 At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
1577 then there is no limit on the number of splits:
1579 >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))
1580 [[0], [2], [4, 5, 6, 7, 8, 9]]
1582 By default, the delimiting items are not included in the output.
1583 To include them, set *keep_separator* to ``True``.
1585 >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
1586 [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]
1588 """
1589 if maxsplit == 0:
1590 yield list(iterable)
1591 return
1593 buf = []
1594 it = iter(iterable)
1595 for item in it:
1596 if pred(item):
1597 yield buf
1598 if keep_separator:
1599 yield [item]
1600 if maxsplit == 1:
1601 yield list(it)
1602 return
1603 buf = []
1604 maxsplit -= 1
1605 else:
1606 buf.append(item)
1607 yield buf
1610def split_before(iterable, pred, maxsplit=-1):
1611 """Yield lists of items from *iterable*, where each list ends just before
1612 an item for which callable *pred* returns ``True``:
1614 >>> list(split_before('OneTwo', lambda s: s.isupper()))
1615 [['O', 'n', 'e'], ['T', 'w', 'o']]
1617 >>> list(split_before(range(10), lambda n: n % 3 == 0))
1618 [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
1620 At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
1621 then there is no limit on the number of splits:
1623 >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))
1624 [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
1625 """
1626 if maxsplit == 0:
1627 buf = list(iterable)
1628 if buf:
1629 yield buf
1630 return
1632 buf = []
1633 it = iter(iterable)
1634 for item in it:
1635 if pred(item) and buf:
1636 yield buf
1637 if maxsplit == 1:
1638 yield [item, *it]
1639 return
1640 buf = []
1641 maxsplit -= 1
1642 buf.append(item)
1643 if buf:
1644 yield buf
1647def split_after(iterable, pred, maxsplit=-1):
1648 """Yield lists of items from *iterable*, where each list ends with an
1649 item where callable *pred* returns ``True``:
1651 >>> list(split_after('one1two2', lambda s: s.isdigit()))
1652 [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]
1654 >>> list(split_after(range(10), lambda n: n % 3 == 0))
1655 [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
1657 At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
1658 then there is no limit on the number of splits:
1660 >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2))
1661 [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]]
1663 """
1664 if maxsplit == 0:
1665 buf = list(iterable)
1666 if buf:
1667 yield buf
1668 return
1670 buf = []
1671 it = iter(iterable)
1672 for item in it:
1673 buf.append(item)
1674 if pred(item) and buf:
1675 yield buf
1676 if maxsplit == 1:
1677 buf = list(it)
1678 if buf:
1679 yield buf
1680 return
1681 buf = []
1682 maxsplit -= 1
1683 if buf:
1684 yield buf
1687def split_when(iterable, pred, maxsplit=-1):
1688 """Split *iterable* into pieces based on the output of *pred*.
1689 *pred* should be a function that takes successive pairs of items and
1690 returns ``True`` if the iterable should be split in between them.
1692 For example, to find runs of increasing numbers, split the iterable when
1693 element ``i`` is larger than element ``i + 1``:
1695 >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y))
1696 [[1, 2, 3, 3], [2, 5], [2, 4], [2]]
1698 At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
1699 then there is no limit on the number of splits:
1701 >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2],
1702 ... lambda x, y: x > y, maxsplit=2))
1703 [[1, 2, 3, 3], [2, 5], [2, 4, 2]]
1705 """
1706 if maxsplit == 0:
1707 buf = list(iterable)
1708 if buf:
1709 yield buf
1710 return
1712 it = iter(iterable)
1713 try:
1714 cur_item = next(it)
1715 except StopIteration:
1716 return
1718 buf = [cur_item]
1719 for next_item in it:
1720 if pred(cur_item, next_item):
1721 yield buf
1722 if maxsplit == 1:
1723 yield [next_item, *it]
1724 return
1725 buf = []
1726 maxsplit -= 1
1728 buf.append(next_item)
1729 cur_item = next_item
1731 yield buf
1734def split_into(iterable, sizes):
1735 """Yield a list of sequential items from *iterable* of length 'n' for each
1736 integer 'n' in *sizes*.
1738 >>> list(split_into([1,2,3,4,5,6], [1,2,3]))
1739 [[1], [2, 3], [4, 5, 6]]
1741 If the sum of *sizes* is smaller than the length of *iterable*, then the
1742 remaining items of *iterable* will not be returned.
1744 >>> list(split_into([1,2,3,4,5,6], [2,3]))
1745 [[1, 2], [3, 4, 5]]
1747 If the sum of *sizes* is larger than the length of *iterable*, fewer items
1748 will be returned in the iteration that overruns the *iterable* and further
1749 lists will be empty:
1751 >>> list(split_into([1,2,3,4], [1,2,3,4]))
1752 [[1], [2, 3], [4], []]
1754 When a ``None`` object is encountered in *sizes*, the returned list will
1755 contain items up to the end of *iterable* the same way that
1756 :func:`itertools.slice` does:
1758 >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))
1759 [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]
1761 :func:`split_into` can be useful for grouping a series of items where the
1762 sizes of the groups are not uniform. An example would be where in a row
1763 from a table, multiple columns represent elements of the same feature
1764 (e.g. a point represented by x,y,z) but, the format is not the same for
1765 all columns.
1766 """
1767 # convert the iterable argument into an iterator so its contents can
1768 # be consumed by islice in case it is a generator
1769 it = iter(iterable)
1771 for size in sizes:
1772 if size is None:
1773 yield list(it)
1774 return
1775 else:
1776 yield list(islice(it, size))
1779def padded(iterable, fillvalue=None, n=None, next_multiple=False):
1780 """Yield the elements from *iterable*, followed by *fillvalue*, such that
1781 at least *n* items are emitted.
1783 >>> list(padded([1, 2, 3], '?', 5))
1784 [1, 2, 3, '?', '?']
1786 If *next_multiple* is ``True``, *fillvalue* will be emitted until the
1787 number of items emitted is a multiple of *n*:
1789 >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))
1790 [1, 2, 3, 4, None, None]
1792 If *n* is ``None``, *fillvalue* will be emitted indefinitely.
1794 To create an *iterable* of exactly size *n*, you can truncate with
1795 :func:`islice`.
1797 >>> list(islice(padded([1, 2, 3], '?'), 5))
1798 [1, 2, 3, '?', '?']
1799 >>> list(islice(padded([1, 2, 3, 4, 5, 6, 7, 8], '?'), 5))
1800 [1, 2, 3, 4, 5]
1802 """
1803 iterator = iter(iterable)
1804 iterator_with_repeat = chain(iterator, repeat(fillvalue))
1806 if n is None:
1807 return iterator_with_repeat
1808 elif n < 1:
1809 raise ValueError('n must be at least 1')
1810 elif next_multiple:
1812 def slice_generator():
1813 for first in iterator:
1814 yield (first,)
1815 yield islice(iterator_with_repeat, n - 1)
1817 # While elements exist produce slices of size n
1818 return chain.from_iterable(slice_generator())
1819 else:
1820 # Ensure the first batch is at least size n then iterate
1821 return chain(islice(iterator_with_repeat, n), iterator)
1824def repeat_each(iterable, n=2):
1825 """Repeat each element in *iterable* *n* times.
1827 >>> list(repeat_each('ABC', 3))
1828 ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
1829 """
1830 return chain.from_iterable(map(repeat, iterable, repeat(n)))
1833def repeat_last(iterable, default=None):
1834 """After the *iterable* is exhausted, keep yielding its last element.
1836 >>> list(islice(repeat_last(range(3)), 5))
1837 [0, 1, 2, 2, 2]
1839 If the iterable is empty, yield *default* forever::
1841 >>> list(islice(repeat_last(range(0), 42), 5))
1842 [42, 42, 42, 42, 42]
1844 """
1845 item = _marker
1846 for item in iterable:
1847 yield item
1848 final = default if item is _marker else item
1849 yield from repeat(final)
1852def distribute(n, iterable):
1853 """Distribute the items from *iterable* among *n* smaller iterables.
1855 >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
1856 >>> list(group_1)
1857 [1, 3, 5]
1858 >>> list(group_2)
1859 [2, 4, 6]
1861 If the length of *iterable* is not evenly divisible by *n*, then the
1862 length of the returned iterables will not be identical:
1864 >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7])
1865 >>> [list(c) for c in children]
1866 [[1, 4, 7], [2, 5], [3, 6]]
1868 If the length of *iterable* is smaller than *n*, then the last returned
1869 iterables will be empty:
1871 >>> children = distribute(5, [1, 2, 3])
1872 >>> [list(c) for c in children]
1873 [[1], [2], [3], [], []]
1875 This function uses :func:`itertools.tee` and may require significant
1876 storage.
1878 If you need the order items in the smaller iterables to match the
1879 original iterable, see :func:`divide`.
1881 """
1882 if n < 1:
1883 raise ValueError('n must be at least 1')
1885 children = tee(iterable, n)
1886 return [islice(it, index, None, n) for index, it in enumerate(children)]
1889def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):
1890 """Yield tuples whose elements are offset from *iterable*.
1891 The amount by which the `i`-th item in each tuple is offset is given by
1892 the `i`-th item in *offsets*.
1894 >>> list(stagger([0, 1, 2, 3]))
1895 [(None, 0, 1), (0, 1, 2), (1, 2, 3)]
1896 >>> list(stagger(range(8), offsets=(0, 2, 4)))
1897 [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)]
1899 By default, the sequence will end when the final element of a tuple is the
1900 last item in the iterable. To continue until the first element of a tuple
1901 is the last item in the iterable, set *longest* to ``True``::
1903 >>> list(stagger([0, 1, 2, 3], longest=True))
1904 [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]
1906 By default, ``None`` will be used to replace offsets beyond the end of the
1907 sequence. Specify *fillvalue* to use some other value.
1909 """
1910 children = tee(iterable, len(offsets))
1912 return zip_offset(
1913 *children, offsets=offsets, longest=longest, fillvalue=fillvalue
1914 )
1917def zip_offset(*iterables, offsets, longest=False, fillvalue=None):
1918 """``zip`` the input *iterables* together, but offset the `i`-th iterable
1919 by the `i`-th item in *offsets*.
1921 >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1)))
1922 [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')]
1924 This can be used as a lightweight alternative to SciPy or pandas to analyze
1925 data sets in which some series have a lead or lag relationship.
1927 By default, the sequence will end when the shortest iterable is exhausted.
1928 To continue until the longest iterable is exhausted, set *longest* to
1929 ``True``.
1931 >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True))
1932 [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')]
1934 By default, ``None`` will be used to replace offsets beyond the end of the
1935 sequence. Specify *fillvalue* to use some other value.
1937 """
1938 if len(iterables) != len(offsets):
1939 raise ValueError("Number of iterables and offsets didn't match")
1941 staggered = []
1942 for it, n in zip(iterables, offsets):
1943 if n < 0:
1944 staggered.append(chain(repeat(fillvalue, -n), it))
1945 elif n > 0:
1946 staggered.append(islice(it, n, None))
1947 else:
1948 staggered.append(it)
1950 if longest:
1951 return zip_longest(*staggered, fillvalue=fillvalue)
1953 return zip(*staggered)
1956def sort_together(
1957 iterables, key_list=(0,), key=None, reverse=False, strict=False
1958):
1959 """Return the input iterables sorted together, with *key_list* as the
1960 priority for sorting. All iterables are trimmed to the length of the
1961 shortest one.
1963 This can be used like the sorting function in a spreadsheet. If each
1964 iterable represents a column of data, the key list determines which
1965 columns are used for sorting.
1967 By default, all iterables are sorted using the ``0``-th iterable::
1969 >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]
1970 >>> sort_together(iterables)
1971 [(1, 2, 3, 4), ('d', 'c', 'b', 'a')]
1973 Set a different key list to sort according to another iterable.
1974 Specifying multiple keys dictates how ties are broken::
1976 >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]
1977 >>> sort_together(iterables, key_list=(1, 2))
1978 [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]
1980 To sort by a function of the elements of the iterable, pass a *key*
1981 function. Its arguments are the elements of the iterables corresponding to
1982 the key list::
1984 >>> names = ('a', 'b', 'c')
1985 >>> lengths = (1, 2, 3)
1986 >>> widths = (5, 2, 1)
1987 >>> def area(length, width):
1988 ... return length * width
1989 >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area)
1990 [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)]
1992 Set *reverse* to ``True`` to sort in descending order.
1994 >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)
1995 [(3, 2, 1), ('a', 'b', 'c')]
1997 If the *strict* keyword argument is ``True``, then
1998 ``ValueError`` will be raised if any of the iterables have
1999 different lengths.
2001 """
2002 if key is None:
2003 # if there is no key function, the key argument to sorted is an
2004 # itemgetter
2005 key_argument = itemgetter(*key_list)
2006 else:
2007 # if there is a key function, call it with the items at the offsets
2008 # specified by the key function as arguments
2009 key_list = list(key_list)
2010 if len(key_list) == 1:
2011 # if key_list contains a single item, pass the item at that offset
2012 # as the only argument to the key function
2013 key_offset = key_list[0]
2014 key_argument = lambda zipped_items: key(zipped_items[key_offset])
2015 else:
2016 # if key_list contains multiple items, use itemgetter to return a
2017 # tuple of items, which we pass as *args to the key function
2018 get_key_items = itemgetter(*key_list)
2019 key_argument = lambda zipped_items: key(
2020 *get_key_items(zipped_items)
2021 )
2023 transposed = zip(*iterables, strict=strict)
2024 reordered = sorted(transposed, key=key_argument, reverse=reverse)
2025 untransposed = zip(*reordered, strict=strict)
2026 return list(untransposed)
2029def unzip(iterable):
2030 """The inverse of :func:`zip`, this function disaggregates the elements
2031 of the zipped *iterable*.
2033 The ``i``-th iterable contains the ``i``-th element from each element
2034 of the zipped iterable. The first element is used to determine the
2035 length of the remaining elements.
2037 >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
2038 >>> letters, numbers = unzip(iterable)
2039 >>> list(letters)
2040 ['a', 'b', 'c', 'd']
2041 >>> list(numbers)
2042 [1, 2, 3, 4]
2044 This is similar to using ``zip(*iterable)``, but it avoids reading
2045 *iterable* into memory. Note, however, that this function uses
2046 :func:`itertools.tee` and thus may require significant storage.
2048 """
2049 head, iterable = spy(iterable)
2050 if not head:
2051 # empty iterable, e.g. zip([], [], [])
2052 return ()
2053 # spy returns a one-length iterable as head
2054 head = head[0]
2055 iterables = tee(iterable, len(head))
2057 # If we have an iterable like iter([(1, 2, 3), (4, 5), (6,)]),
2058 # the second unzipped iterable fails at the third tuple since
2059 # it tries to access (6,)[1].
2060 # Same with the third unzipped iterable and the second tuple.
2061 # To support these "improperly zipped" iterables, we suppress
2062 # the IndexError, which just stops the unzipped iterables at
2063 # first length mismatch.
2064 return tuple(
2065 iter_suppress(map(itemgetter(i), it), IndexError)
2066 for i, it in enumerate(iterables)
2067 )
2070def divide(n, iterable):
2071 """Divide the elements from *iterable* into *n* parts, maintaining
2072 order.
2074 >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])
2075 >>> list(group_1)
2076 [1, 2, 3]
2077 >>> list(group_2)
2078 [4, 5, 6]
2080 If the length of *iterable* is not evenly divisible by *n*, then the
2081 length of the returned iterables will not be identical:
2083 >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])
2084 >>> [list(c) for c in children]
2085 [[1, 2, 3], [4, 5], [6, 7]]
2087 If the length of the iterable is smaller than n, then the last returned
2088 iterables will be empty:
2090 >>> children = divide(5, [1, 2, 3])
2091 >>> [list(c) for c in children]
2092 [[1], [2], [3], [], []]
2094 This function will exhaust the iterable before returning.
2095 If order is not important, see :func:`distribute`, which does not first
2096 pull the iterable into memory.
2098 """
2099 if n < 1:
2100 raise ValueError('n must be at least 1')
2102 try:
2103 iterable[:0]
2104 except TypeError:
2105 seq = tuple(iterable)
2106 else:
2107 seq = iterable
2109 q, r = divmod(len(seq), n)
2111 ret = []
2112 stop = 0
2113 for i in range(1, n + 1):
2114 start = stop
2115 stop += q + 1 if i <= r else q
2116 ret.append(iter(seq[start:stop]))
2118 return ret
2121def always_iterable(obj, base_type=(str, bytes)):
2122 """If *obj* is iterable, return an iterator over its items::
2124 >>> obj = (1, 2, 3)
2125 >>> list(always_iterable(obj))
2126 [1, 2, 3]
2128 If *obj* is not iterable, return a one-item iterable containing *obj*::
2130 >>> obj = 1
2131 >>> list(always_iterable(obj))
2132 [1]
2134 If *obj* is ``None``, return an empty iterable:
2136 >>> obj = None
2137 >>> list(always_iterable(None))
2138 []
2140 By default, binary and text strings are not considered iterable::
2142 >>> obj = 'foo'
2143 >>> list(always_iterable(obj))
2144 ['foo']
2146 If *base_type* is set, objects for which ``isinstance(obj, base_type)``
2147 returns ``True`` won't be considered iterable.
2149 >>> obj = {'a': 1}
2150 >>> list(always_iterable(obj)) # Iterate over the dict's keys
2151 ['a']
2152 >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
2153 [{'a': 1}]
2155 Set *base_type* to ``None`` to avoid any special handling and treat objects
2156 Python considers iterable as iterable:
2158 >>> obj = 'foo'
2159 >>> list(always_iterable(obj, base_type=None))
2160 ['f', 'o', 'o']
2161 """
2162 if obj is None:
2163 return iter(())
2165 if (base_type is not None) and isinstance(obj, base_type):
2166 return iter((obj,))
2168 try:
2169 return iter(obj)
2170 except TypeError:
2171 return iter((obj,))
2174def adjacent(predicate, iterable, distance=1):
2175 """Return an iterable over `(bool, item)` tuples where the `item` is
2176 drawn from *iterable* and the `bool` indicates whether
2177 that item satisfies the *predicate* or is adjacent to an item that does.
2179 For example, to find whether items are adjacent to a ``3``::
2181 >>> list(adjacent(lambda x: x == 3, range(6)))
2182 [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)]
2184 Set *distance* to change what counts as adjacent. For example, to find
2185 whether items are two places away from a ``3``:
2187 >>> list(adjacent(lambda x: x == 3, range(6), distance=2))
2188 [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)]
2190 This is useful for contextualizing the results of a search function.
2191 For example, a code comparison tool might want to identify lines that
2192 have changed, but also surrounding lines to give the viewer of the diff
2193 context.
2195 The predicate function will only be called once for each item in the
2196 iterable.
2198 See also :func:`groupby_transform`, which can be used with this function
2199 to group ranges of items with the same `bool` value.
2201 """
2202 # Allow distance=0 mainly for testing that it reproduces results with map()
2203 if distance < 0:
2204 raise ValueError('distance must be at least 0')
2206 i1, i2 = tee(iterable)
2207 padding = [False] * distance
2208 selected = chain(padding, map(predicate, i1), padding)
2209 adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1))
2210 return zip(adjacent_to_selected, i2)
2213def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None):
2214 """An extension of :func:`itertools.groupby` that can apply transformations
2215 to the grouped data.
2217 * *keyfunc* is a function computing a key value for each item in *iterable*
2218 * *valuefunc* is a function that transforms the individual items from
2219 *iterable* after grouping
2220 * *reducefunc* is a function that transforms each group of items
2222 >>> iterable = 'aAAbBBcCC'
2223 >>> keyfunc = lambda k: k.upper()
2224 >>> valuefunc = lambda v: v.lower()
2225 >>> reducefunc = lambda g: ''.join(g)
2226 >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc))
2227 [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')]
2229 Each optional argument defaults to an identity function if not specified.
2231 :func:`groupby_transform` is useful when grouping elements of an iterable
2232 using a separate iterable as the key. To do this, :func:`zip` the iterables
2233 and pass a *keyfunc* that extracts the first element and a *valuefunc*
2234 that extracts the second element::
2236 >>> from operator import itemgetter
2237 >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3]
2238 >>> values = 'abcdefghi'
2239 >>> iterable = zip(keys, values)
2240 >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1))
2241 >>> [(k, ''.join(g)) for k, g in grouper]
2242 [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')]
2244 Note that the order of items in the iterable is significant.
2245 Only adjacent items are grouped together, so if you don't want any
2246 duplicate groups, you should sort the iterable by the key function
2247 or consider :func:`bucket` or :func:`map_reduce`. :func:`map_reduce`
2248 consumes the iterable immediately and returns a dictionary, while
2249 :func:`bucket` does not.
2251 .. seealso:: :func:`bucket`, :func:`map_reduce`
2253 """
2254 ret = groupby(iterable, keyfunc)
2255 if valuefunc:
2256 ret = ((k, map(valuefunc, g)) for k, g in ret)
2257 if reducefunc:
2258 ret = ((k, reducefunc(g)) for k, g in ret)
2260 return ret
2263class numeric_range(Sequence):
2264 """An extension of the built-in ``range()`` function whose arguments can
2265 be any orderable numeric type.
2267 With only *stop* specified, *start* defaults to ``0`` and *step*
2268 defaults to ``1``. The output items will match the type of *stop*:
2270 >>> list(numeric_range(3.5))
2271 [0.0, 1.0, 2.0, 3.0]
2273 With only *start* and *stop* specified, *step* defaults to ``1``, typed
2274 to match *stop* - *start*. The output items will match the type of
2275 ``start + step``:
2277 >>> from decimal import Decimal
2278 >>> start = Decimal('2.1')
2279 >>> stop = Decimal('5.1')
2280 >>> list(numeric_range(start, stop))
2281 [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')]
2283 With *start*, *stop*, and *step* specified the output items will match
2284 the type of ``start + step``:
2286 >>> from fractions import Fraction
2287 >>> start = Fraction(1, 2) # Start at 1/2
2288 >>> stop = Fraction(5, 2) # End at 5/2
2289 >>> step = Fraction(1, 2) # Count by 1/2
2290 >>> list(numeric_range(start, stop, step))
2291 [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)]
2293 If *step* is zero, ``ValueError`` is raised. Negative steps are supported:
2295 >>> list(numeric_range(3, -1, -1.0))
2296 [3.0, 2.0, 1.0, 0.0]
2298 Be aware of the limitations of floating-point numbers; the representation
2299 of the yielded numbers may be surprising.
2301 ``datetime.datetime`` objects can be used for *start* and *stop*, if *step*
2302 is a ``datetime.timedelta`` object:
2304 >>> import datetime
2305 >>> start = datetime.datetime(2019, 1, 1)
2306 >>> stop = datetime.datetime(2019, 1, 3)
2307 >>> step = datetime.timedelta(days=1)
2308 >>> items = iter(numeric_range(start, stop, step))
2309 >>> next(items)
2310 datetime.datetime(2019, 1, 1, 0, 0)
2311 >>> next(items)
2312 datetime.datetime(2019, 1, 2, 0, 0)
2314 """
2316 _EMPTY_HASH = hash(range(0, 0))
2318 def __init__(self, *args):
2319 argc = len(args)
2320 if argc == 1:
2321 (self._stop,) = args
2322 self._start = type(self._stop)(0)
2323 self._step = type(self._stop - self._start)(1)
2324 elif argc == 2:
2325 self._start, self._stop = args
2326 self._step = type(self._stop - self._start)(1)
2327 elif argc == 3:
2328 self._start, self._stop, self._step = args
2329 elif argc == 0:
2330 raise TypeError(
2331 f'numeric_range expected at least 1 argument, got {argc}'
2332 )
2333 else:
2334 raise TypeError(
2335 f'numeric_range expected at most 3 arguments, got {argc}'
2336 )
2338 self._zero = type(self._step)(0)
2339 if self._step == self._zero:
2340 raise ValueError('numeric_range() arg 3 must not be zero')
2341 self._growing = self._step > self._zero
2343 def __bool__(self):
2344 if self._growing:
2345 return self._start < self._stop
2346 else:
2347 return self._start > self._stop
2349 def __contains__(self, elem):
2350 try:
2351 self.index(elem)
2352 except ValueError:
2353 return False
2354 return True
2356 def __eq__(self, other):
2357 # numeric_range object equality is intended to mirror the built-in range
2358 # object's equality.
2359 # https://github.com/python/cpython/blob/f5c4880151b609e0a0a0b05c292d36b18038c061/Objects/rangeobject.c#L499
2360 if not isinstance(other, numeric_range):
2361 return False
2363 if self is other:
2364 return True
2366 len_self = len(self)
2367 if len_self != len(other):
2368 return False
2370 if not len_self:
2371 return True
2373 if self._start != other._start:
2374 return False
2376 if len_self == 1:
2377 return True
2379 return self._step == other._step
2381 def __getitem__(self, key):
2382 if isinstance(key, int):
2383 return self._get_by_index(key)
2384 elif isinstance(key, slice):
2385 start_idx, stop_idx, step_idx = key.indices(self._len)
2386 return numeric_range(
2387 self._start + start_idx * self._step,
2388 self._start + stop_idx * self._step,
2389 self._step * step_idx,
2390 )
2391 else:
2392 raise TypeError(
2393 'numeric range indices must be '
2394 f'integers or slices, not {type(key).__name__}'
2395 )
2397 def __hash__(self):
2398 # numeric_range hashing is intended to mirror the built-in range object's
2399 # hashing.
2400 # https://github.com/python/cpython/blob/f5c4880151b609e0a0a0b05c292d36b18038c061/Objects/rangeobject.c#L570
2401 len_self = len(self)
2402 if not len_self:
2403 return hash((len_self, None, None))
2404 if len_self == 1:
2405 return hash((len_self, self._start, None))
2406 return hash((len_self, self._start, self._step))
2408 def __iter__(self):
2409 values = (self._start + (n * self._step) for n in count())
2410 if self._growing:
2411 return takewhile(partial(gt, self._stop), values)
2412 else:
2413 return takewhile(partial(lt, self._stop), values)
2415 def __len__(self):
2416 return self._len
2418 @cached_property
2419 def _len(self):
2420 if self._growing:
2421 start = self._start
2422 stop = self._stop
2423 step = self._step
2424 else:
2425 start = self._stop
2426 stop = self._start
2427 step = -self._step
2428 distance = stop - start
2429 if distance <= self._zero:
2430 return 0
2431 else: # distance > 0 and step > 0: regular euclidean division
2432 q, r = divmod(distance, step)
2433 n = int(q) + int(r != self._zero)
2434 # The division above measures the distance to cover, but the items
2435 # are produced by repeated multiplication (see `__iter__`). With
2436 # inexact arithmetic the two disagree at the boundary, so settle
2437 # the count against the items themselves.
2438 while n and not self._before_stop(n - 1):
2439 n -= 1
2440 while self._before_stop(n):
2441 n += 1
2442 return n
2444 def _before_stop(self, i):
2445 value = self._start + i * self._step
2446 return value < self._stop if self._growing else value > self._stop
2448 def __reduce__(self):
2449 return numeric_range, (self._start, self._stop, self._step)
2451 def __repr__(self):
2452 if self._step == 1:
2453 return f"numeric_range({self._start!r}, {self._stop!r})"
2454 return (
2455 f"numeric_range({self._start!r}, {self._stop!r}, {self._step!r})"
2456 )
2458 def __reversed__(self):
2459 start = self._start
2460 step = self._step
2461 for i in reversed(range(self._len)):
2462 yield start + i * step
2464 def count(self, value):
2465 return int(value in self)
2467 def index(self, value):
2468 if self._growing:
2469 if self._start <= value < self._stop:
2470 q, _ = divmod(value - self._start, self._step)
2471 return self._index_near(int(q), value)
2472 else:
2473 if self._start >= value > self._stop:
2474 q, _ = divmod(self._start - value, -self._step)
2475 return self._index_near(int(q), value)
2477 raise ValueError(f"{value} is not in numeric range")
2479 def _index_near(self, i, value):
2480 # `i` is the quotient of the division of `value` by the step, which
2481 # locates the value on the grid of items this range produces. For
2482 # exact types that quotient is the index. For inexact ones (floats)
2483 # it can land one short, and the remainder of the division is not a
2484 # reliable membership test either: `numeric_range(0.0, 1.0, 0.1)`
2485 # yields 0.30000000000000004, which leaves a non-zero remainder.
2486 # So compare against the item the range actually produces there.
2487 for candidate in (i, i + 1):
2488 if 0 <= candidate < self._len:
2489 if self._start + candidate * self._step == value:
2490 return candidate
2492 raise ValueError(f"{value} is not in numeric range")
2494 def _get_by_index(self, i):
2495 if i < 0:
2496 i += self._len
2497 if i < 0 or i >= self._len:
2498 raise IndexError("numeric range object index out of range")
2499 return self._start + i * self._step
2502def count_cycle(iterable, n=None):
2503 """Cycle through the items from *iterable* up to *n* times, yielding
2504 the number of completed cycles along with each item. If *n* is omitted the
2505 process repeats indefinitely.
2507 >>> list(count_cycle('AB', 3))
2508 [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
2510 """
2511 if n is not None:
2512 return product(range(n), iterable)
2513 seq = tuple(iterable)
2514 if not seq:
2515 return iter(())
2516 return zip(repeat_each(count(), len(seq)), cycle(seq))
2519def mark_ends(iterable):
2520 """Yield 3-tuples of the form ``(is_first, is_last, item)``.
2522 >>> list(mark_ends('ABC'))
2523 [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')]
2525 Use this when looping over an iterable to take special action on its first
2526 and/or last items:
2528 >>> iterable = ['Header', 100, 200, 'Footer']
2529 >>> total = 0
2530 >>> for is_first, is_last, item in mark_ends(iterable):
2531 ... if is_first:
2532 ... continue # Skip the header
2533 ... if is_last:
2534 ... continue # Skip the footer
2535 ... total += item
2536 >>> print(total)
2537 300
2538 """
2539 it = iter(iterable)
2540 for a in it:
2541 first = True
2542 for b in it:
2543 yield first, False, a
2544 a = b
2545 first = False
2546 yield first, True, a
2549def locate(iterable, pred=bool, window_size=None):
2550 """Yield the index of each item in *iterable* for which *pred* returns
2551 ``True``.
2553 *pred* defaults to :func:`bool`, which will select truthy items:
2555 >>> list(locate([0, 1, 1, 0, 1, 0, 0]))
2556 [1, 2, 4]
2558 Set *pred* to a custom function to, e.g., find the indexes for a particular
2559 item.
2561 >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
2562 [1, 3]
2564 If *window_size* is given, then the *pred* function will be called with
2565 the values in each window. This enables searching for sub-sequences.
2566 Note that *pred* may receive fewer than *window_size* arguments at the end of
2567 the iterable.
2569 >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
2570 >>> pred = lambda *args: args == (1, 2, 3)
2571 >>> list(locate(iterable, pred=pred, window_size=3))
2572 [1, 5, 9]
2574 Use with :func:`seekable` to find indexes and then retrieve the associated
2575 items:
2577 >>> from itertools import count
2578 >>> from more_itertools import seekable
2579 >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count())
2580 >>> it = seekable(source)
2581 >>> pred = lambda x: x > 100
2582 >>> indexes = locate(it, pred=pred)
2583 >>> i = next(indexes)
2584 >>> it.seek(i)
2585 >>> next(it)
2586 106
2588 """
2589 if window_size is None:
2590 return compress(count(), map(pred, iterable))
2592 if window_size < 1:
2593 raise ValueError('window size must be at least 1')
2595 it = windowed(iterable, window_size, fillvalue=_marker)
2596 return compress(
2597 count(),
2598 (pred(*(x for x in w if x is not _marker)) for w in it),
2599 )
2602def longest_common_prefix(iterables):
2603 """Yield elements of the longest common prefix among given *iterables*.
2605 >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf']))
2606 'ab'
2608 """
2609 return (c[0] for c in takewhile(all_equal, zip(*iterables)))
2612def lstrip(iterable, pred):
2613 """Yield the items from *iterable*, but strip any from the beginning
2614 for which *pred* returns ``True``.
2616 For example, to remove a set of items from the start of an iterable:
2618 >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
2619 >>> pred = lambda x: x in {None, False, ''}
2620 >>> list(lstrip(iterable, pred))
2621 [1, 2, None, 3, False, None]
2623 This function is analogous to :func:`str.lstrip`, and is essentially
2624 a wrapper for :func:`itertools.dropwhile`.
2626 """
2627 return dropwhile(pred, iterable)
2630def rstrip(iterable, pred):
2631 """Yield the items from *iterable*, but strip any from the end
2632 for which *pred* returns ``True``.
2634 For example, to remove a set of items from the end of an iterable:
2636 >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
2637 >>> pred = lambda x: x in {None, False, ''}
2638 >>> list(rstrip(iterable, pred))
2639 [None, False, None, 1, 2, None, 3]
2641 This function is analogous to :func:`str.rstrip`.
2643 """
2644 cache = []
2645 cache_append = cache.append
2646 cache_clear = cache.clear
2647 for x in iterable:
2648 if pred(x):
2649 cache_append(x)
2650 else:
2651 yield from cache
2652 cache_clear()
2653 yield x
2656def strip(iterable, pred):
2657 """Yield the items from *iterable*, but strip any from the
2658 beginning and end for which *pred* returns ``True``.
2660 For example, to remove a set of items from both ends of an iterable:
2662 >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
2663 >>> pred = lambda x: x in {None, False, ''}
2664 >>> list(strip(iterable, pred))
2665 [1, 2, None, 3]
2667 This function is analogous to :func:`str.strip`.
2669 """
2670 return rstrip(lstrip(iterable, pred), pred)
2673class islice_extended:
2674 """An extension of :func:`itertools.islice` that supports negative values
2675 for *stop*, *start*, and *step*.
2677 >>> iterator = iter('abcdefgh')
2678 >>> list(islice_extended(iterator, -4, -1))
2679 ['e', 'f', 'g']
2681 Slices with negative values require some caching of *iterable*, but this
2682 function takes care to minimize the amount of memory required.
2684 For example, you can use a negative step with an infinite iterator:
2686 >>> from itertools import count
2687 >>> list(islice_extended(count(), 110, 99, -2))
2688 [110, 108, 106, 104, 102, 100]
2690 You can also use slice notation directly:
2692 >>> iterator = map(str, count())
2693 >>> it = islice_extended(iterator)[10:20:2]
2694 >>> list(it)
2695 ['10', '12', '14', '16', '18']
2697 """
2699 def __init__(self, iterable, *args):
2700 it = iter(iterable)
2701 if args:
2702 self._iterator = _islice_helper(it, slice(*args))
2703 else:
2704 self._iterator = it
2706 def __iter__(self):
2707 return self
2709 def __next__(self):
2710 return next(self._iterator)
2712 def __getitem__(self, key):
2713 if isinstance(key, slice):
2714 return islice_extended(_islice_helper(self._iterator, key))
2716 raise TypeError('islice_extended.__getitem__ argument must be a slice')
2719def _islice_helper(it, s):
2720 start = s.start
2721 stop = s.stop
2722 if s.step == 0:
2723 raise ValueError('step argument must be a non-zero integer or None.')
2724 step = s.step or 1
2726 if step > 0:
2727 start = 0 if (start is None) else start
2729 if start < 0:
2730 # Consume all but the last -start items
2731 counter = count(1)
2732 wrapper = compress(it, counter)
2733 cache = deque(wrapper, maxlen=-start)
2734 len_iter = next(counter) - 1
2736 # Adjust start to be positive
2737 i = max(len_iter + start, 0)
2739 # Adjust stop to be positive
2740 if stop is None:
2741 j = len_iter
2742 elif stop >= 0:
2743 j = min(stop, len_iter)
2744 else:
2745 j = max(len_iter + stop, 0)
2747 # Slice the cache
2748 n = j - i
2749 if n <= 0:
2750 return
2752 for index in range(n):
2753 if index % step == 0:
2754 # pop and yield the item.
2755 # We don't want to use an intermediate variable
2756 # it would extend the lifetime of the current item
2757 yield cache.popleft()
2758 else:
2759 # just pop and discard the item
2760 cache.popleft()
2761 elif (stop is not None) and (stop < 0):
2762 # Advance to the start position
2763 next(islice(it, start, start), None)
2765 # When stop is negative, we have to carry -stop items while
2766 # iterating
2767 cache = deque(islice(it, -stop), maxlen=-stop)
2769 for index, item in enumerate(it):
2770 if index % step == 0:
2771 # pop and yield the item.
2772 # We don't want to use an intermediate variable
2773 # it would extend the lifetime of the current item
2774 yield cache.popleft()
2775 else:
2776 # just pop and discard the item
2777 cache.popleft()
2778 cache.append(item)
2779 else:
2780 # When both start and stop are positive we have the normal case
2781 yield from islice(it, start, stop, step)
2782 else:
2783 start = -1 if (start is None) else start
2785 if (stop is not None) and (stop < 0):
2786 # Consume all but the last items
2787 n = -stop - 1
2788 counter = count(1)
2789 wrapper = compress(it, counter)
2790 cache = deque(wrapper, maxlen=n)
2791 len_iter = next(counter) - 1
2793 # If start and stop are both negative they are comparable and
2794 # we can just slice. Otherwise we can adjust start to be negative
2795 # and then slice.
2796 if start < 0:
2797 i, j = start, stop
2798 else:
2799 i, j = min(start - len_iter, -1), None
2801 yield from list(cache)[i:j:step]
2802 else:
2803 # Advance to the stop position
2804 if stop is not None:
2805 m = stop + 1
2806 next(islice(it, m, m), None)
2808 # stop is positive, so if start is negative they are not comparable
2809 # and we need the rest of the items.
2810 if start < 0:
2811 i = start
2812 n = None
2813 # stop is None and start is positive, so we just need items up to
2814 # the start index.
2815 elif stop is None:
2816 i = None
2817 n = start + 1
2818 # Both stop and start are positive, so they are comparable.
2819 else:
2820 i = None
2821 n = start - stop
2822 if n <= 0:
2823 return
2825 cache = list(islice(it, n))
2827 yield from cache[i::step]
2830def always_reversible(iterable):
2831 """An extension of :func:`reversed` that supports all iterables, not
2832 just those which implement the ``Reversible`` or ``Sequence`` protocols.
2834 >>> print(*always_reversible(x for x in range(3)))
2835 2 1 0
2837 If the iterable is already reversible, this function returns the
2838 result of :func:`reversed()`. If the iterable is not reversible,
2839 this function will cache the remaining items in the iterable and
2840 yield them in reverse order, which may require significant storage.
2841 """
2842 try:
2843 return reversed(iterable)
2844 except TypeError:
2845 return reversed(list(iterable))
2848def consecutive_groups(iterable, ordering=None):
2849 """Yield groups of consecutive items using :func:`itertools.groupby`.
2850 The *ordering* function determines whether two items are adjacent by
2851 returning their position.
2853 By default, the ordering function is the identity function. This is
2854 suitable for finding runs of numbers:
2856 >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40]
2857 >>> for group in consecutive_groups(iterable):
2858 ... print(list(group))
2859 [1]
2860 [10, 11, 12]
2861 [20]
2862 [30, 31, 32, 33]
2863 [40]
2865 To find runs of adjacent letters, apply :func:`ord` function
2866 to convert letters to ordinals.
2868 >>> iterable = 'abcdfgilmnop'
2869 >>> ordering = ord
2870 >>> for group in consecutive_groups(iterable, ordering):
2871 ... print(list(group))
2872 ['a', 'b', 'c', 'd']
2873 ['f', 'g']
2874 ['i']
2875 ['l', 'm', 'n', 'o', 'p']
2877 Each group of consecutive items is an iterator that shares its source with
2878 *iterable*. When an output group is advanced, the previous group is
2879 no longer available unless its elements are copied (e.g., into a ``list``).
2881 >>> iterable = [1, 2, 11, 12, 21, 22]
2882 >>> saved_groups = []
2883 >>> for group in consecutive_groups(iterable):
2884 ... saved_groups.append(list(group)) # Copy group elements
2885 >>> saved_groups
2886 [[1, 2], [11, 12], [21, 22]]
2888 """
2889 if ordering is None:
2890 key = lambda x: x[0] - x[1]
2891 else:
2892 key = lambda x: x[0] - ordering(x[1])
2894 for k, g in groupby(enumerate(iterable), key=key):
2895 yield map(itemgetter(1), g)
2898def difference(iterable, func=sub, *, initial=None):
2899 """This function is the inverse of :func:`itertools.accumulate`. By default
2900 it will compute the first difference of *iterable* using
2901 :func:`operator.sub`:
2903 >>> from itertools import accumulate
2904 >>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10
2905 >>> list(difference(iterable))
2906 [0, 1, 2, 3, 4]
2908 *func* defaults to :func:`operator.sub`, but other functions can be
2909 specified. They will be applied as follows::
2911 A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ...
2913 For example, to do progressive division:
2915 >>> iterable = [1, 2, 6, 24, 120]
2916 >>> func = lambda x, y: x // y
2917 >>> list(difference(iterable, func))
2918 [1, 2, 3, 4, 5]
2920 If the *initial* keyword is set, the first element will be skipped when
2921 computing successive differences.
2923 >>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10)
2924 >>> list(difference(it, initial=10))
2925 [1, 2, 3]
2927 """
2928 a, b = tee(iterable)
2929 try:
2930 first = [next(b)]
2931 except StopIteration:
2932 return iter([])
2934 if initial is not None:
2935 return map(func, b, a)
2937 return chain(first, map(func, b, a))
2940class SequenceView(Sequence):
2941 """Return a read-only view of the sequence object *target*.
2943 :class:`SequenceView` objects are analogous to Python's built-in
2944 "dictionary view" types. They provide a dynamic view of a sequence's items,
2945 meaning that when the sequence updates, so does the view.
2947 >>> seq = ['0', '1', '2']
2948 >>> view = SequenceView(seq)
2949 >>> view
2950 SequenceView(['0', '1', '2'])
2951 >>> seq.append('3')
2952 >>> view
2953 SequenceView(['0', '1', '2', '3'])
2955 Sequence views support indexing, slicing, and length queries. They act
2956 like the underlying sequence, except they don't allow assignment:
2958 >>> view[1]
2959 '1'
2960 >>> view[1:-1]
2961 ['1', '2']
2962 >>> len(view)
2963 4
2965 Sequence views are useful as an alternative to copying, as they don't
2966 require (much) extra storage.
2968 """
2970 def __init__(self, target):
2971 if not isinstance(target, Sequence):
2972 raise TypeError
2973 self._target = target
2975 def __getitem__(self, index):
2976 return self._target[index]
2978 def __len__(self):
2979 return len(self._target)
2981 def __repr__(self):
2982 return f'{self.__class__.__name__}({self._target!r})'
2985class seekable:
2986 """Wrap an iterator to allow for seeking backward and forward. This
2987 progressively caches the items in the source iterable so they can be
2988 re-visited.
2990 Call :meth:`seek` with an index to seek to that position in the source
2991 iterable.
2993 To "reset" an iterator, seek to ``0``:
2995 >>> from itertools import count
2996 >>> it = seekable((str(n) for n in count()))
2997 >>> next(it), next(it), next(it)
2998 ('0', '1', '2')
2999 >>> it.seek(0)
3000 >>> next(it), next(it), next(it)
3001 ('0', '1', '2')
3003 You can also seek forward:
3005 >>> it = seekable((str(n) for n in range(20)))
3006 >>> it.seek(10)
3007 >>> next(it)
3008 '10'
3009 >>> it.seek(20) # Seeking past the end of the source isn't a problem
3010 >>> list(it)
3011 []
3012 >>> it.seek(0) # Resetting works even after hitting the end
3013 >>> next(it)
3014 '0'
3016 Call :meth:`relative_seek` to seek relative to the source iterator's
3017 current position.
3019 >>> it = seekable((str(n) for n in range(20)))
3020 >>> next(it), next(it), next(it)
3021 ('0', '1', '2')
3022 >>> it.relative_seek(2)
3023 >>> next(it)
3024 '5'
3025 >>> it.relative_seek(-3) # Source is at '6', we move back to '3'
3026 >>> next(it)
3027 '3'
3028 >>> it.relative_seek(-3) # Source is at '4', we move back to '1'
3029 >>> next(it)
3030 '1'
3033 Call :meth:`peek` to look ahead one item without advancing the iterator:
3035 >>> it = seekable('1234')
3036 >>> it.peek()
3037 '1'
3038 >>> list(it)
3039 ['1', '2', '3', '4']
3040 >>> it.peek(default='empty')
3041 'empty'
3043 Before the iterator is at its end, calling :func:`bool` on it will return
3044 ``True``. After it will return ``False``:
3046 >>> it = seekable('5678')
3047 >>> bool(it)
3048 True
3049 >>> list(it)
3050 ['5', '6', '7', '8']
3051 >>> bool(it)
3052 False
3054 You may view the contents of the cache with the :meth:`elements` method.
3055 That returns a :class:`SequenceView`, a view that updates automatically:
3057 >>> it = seekable((str(n) for n in range(10)))
3058 >>> next(it), next(it), next(it)
3059 ('0', '1', '2')
3060 >>> elements = it.elements()
3061 >>> elements
3062 SequenceView(['0', '1', '2'])
3063 >>> next(it)
3064 '3'
3065 >>> elements
3066 SequenceView(['0', '1', '2', '3'])
3068 Indexing the :class:`seekable` directly returns items from the cache:
3070 >>> it = seekable((str(n) for n in range(10)))
3071 >>> next(it), next(it), next(it)
3072 ('0', '1', '2')
3073 >>> it[-1]
3074 '2'
3075 >>> it[0]
3076 '0'
3078 By default, the cache grows as the source iterable progresses, so beware of
3079 wrapping very large or infinite iterables. Supply *maxlen* to limit the
3080 size of the cache (this of course limits how far back you can seek).
3082 >>> from itertools import count
3083 >>> it = seekable((str(n) for n in count()), maxlen=2)
3084 >>> next(it), next(it), next(it), next(it)
3085 ('0', '1', '2', '3')
3086 >>> list(it.elements())
3087 ['2', '3']
3088 >>> it.seek(0)
3089 >>> next(it), next(it), next(it), next(it)
3090 ('2', '3', '4', '5')
3091 >>> next(it)
3092 '6'
3094 """
3096 def __init__(self, iterable, maxlen=None):
3097 self._maxlen_zero = maxlen == 0
3098 self._source = (
3099 peekable(iterable) if self._maxlen_zero else iter(iterable)
3100 )
3101 if maxlen is None:
3102 self._cache = []
3103 else:
3104 self._cache = deque([], maxlen)
3105 self._index = None
3107 def __iter__(self):
3108 return self
3110 def __next__(self):
3111 if self._index is not None:
3112 try:
3113 item = self._cache[self._index]
3114 except IndexError:
3115 self._index = None
3116 else:
3117 self._index += 1
3118 return item
3120 item = next(self._source)
3121 self._cache.append(item)
3122 return item
3124 def __bool__(self):
3125 try:
3126 self.peek()
3127 except StopIteration:
3128 return False
3129 return True
3131 def peek(self, default=_marker):
3132 if self._maxlen_zero:
3133 return self._source.peek(default)
3134 try:
3135 peeked = next(self)
3136 except StopIteration:
3137 if default is _marker:
3138 raise
3139 return default
3140 if self._index is None:
3141 self._index = len(self._cache)
3142 self._index -= 1
3143 return peeked
3145 def elements(self):
3146 return SequenceView(self._cache)
3148 def seek(self, index):
3149 self._index = index
3150 remainder = index - len(self._cache)
3151 if remainder > 0:
3152 consume(self, remainder)
3154 def relative_seek(self, count):
3155 if self._index is None:
3156 self._index = len(self._cache)
3158 self.seek(max(self._index + count, 0))
3160 def __getitem__(self, index):
3161 return self._cache[index]
3164class run_length:
3165 """
3166 :func:`run_length.encode` compresses an iterable with run-length encoding.
3167 It yields groups of repeated items with the count of how many times they
3168 were repeated:
3170 >>> uncompressed = 'abbcccdddd'
3171 >>> list(run_length.encode(uncompressed))
3172 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
3174 :func:`run_length.decode` decompresses an iterable that was previously
3175 compressed with run-length encoding. It yields the items of the
3176 decompressed iterable:
3178 >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
3179 >>> list(run_length.decode(compressed))
3180 ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']
3182 """
3184 @staticmethod
3185 def encode(iterable):
3186 return ((k, ilen(g)) for k, g in groupby(iterable))
3188 @staticmethod
3189 def decode(iterable):
3190 return chain.from_iterable(starmap(repeat, iterable))
3193def exactly_n(iterable, n, predicate=bool):
3194 """Return ``True`` if exactly ``n`` items in the iterable are ``True``
3195 according to the *predicate* function.
3197 >>> exactly_n([True, True, False], 2)
3198 True
3199 >>> exactly_n([True, True, False], 1)
3200 False
3201 >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3)
3202 True
3204 The iterable will be advanced until ``n + 1`` truthy items are encountered,
3205 so avoid calling it on infinite iterables.
3207 """
3208 iterator = filter(predicate, iterable)
3209 if n <= 0:
3210 if n < 0:
3211 return False
3212 for _ in iterator:
3213 return False
3214 return True
3216 iterator = islice(iterator, n - 1, None)
3217 for _ in iterator:
3218 for _ in iterator:
3219 return False
3220 return True
3221 return False
3224def circular_shifts(iterable, steps=1):
3225 """Yield the circular shifts of *iterable*.
3227 >>> list(circular_shifts(range(4)))
3228 [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]
3230 Set *steps* to the number of places to rotate to the left
3231 (or to the right if negative). Defaults to 1.
3233 >>> list(circular_shifts(range(4), 2))
3234 [(0, 1, 2, 3), (2, 3, 0, 1)]
3236 >>> list(circular_shifts(range(4), -1))
3237 [(0, 1, 2, 3), (3, 0, 1, 2), (2, 3, 0, 1), (1, 2, 3, 0)]
3239 """
3240 buffer = deque(iterable)
3241 if steps == 0:
3242 raise ValueError('Steps should be a non-zero integer')
3244 buffer.rotate(steps)
3245 steps = -steps
3246 n = len(buffer)
3247 n //= math.gcd(n, steps)
3249 for _ in repeat(None, n):
3250 buffer.rotate(steps)
3251 yield tuple(buffer)
3254def make_decorator(wrapping_func, result_index=0):
3255 """Return a decorator version of *wrapping_func*, which is a function that
3256 modifies an iterable. *result_index* is the position in that function's
3257 signature where the iterable goes.
3259 This lets you use itertools on the "production end," i.e. at function
3260 definition. This can augment what the function returns without changing the
3261 function's code.
3263 For example, to produce a decorator version of :func:`chunked`:
3265 >>> from more_itertools import chunked
3266 >>> chunker = make_decorator(chunked, result_index=0)
3267 >>> @chunker(3)
3268 ... def iter_range(n):
3269 ... return iter(range(n))
3270 ...
3271 >>> list(iter_range(9))
3272 [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
3274 To only allow truthy items to be returned:
3276 >>> truth_serum = make_decorator(filter, result_index=1)
3277 >>> @truth_serum(bool)
3278 ... def boolean_test():
3279 ... return [0, 1, '', ' ', False, True]
3280 ...
3281 >>> list(boolean_test())
3282 [1, ' ', True]
3284 The :func:`peekable` and :func:`seekable` wrappers make for practical
3285 decorators:
3287 >>> from more_itertools import peekable
3288 >>> peekable_function = make_decorator(peekable)
3289 >>> @peekable_function()
3290 ... def str_range(*args):
3291 ... return (str(x) for x in range(*args))
3292 ...
3293 >>> it = str_range(1, 20, 2)
3294 >>> next(it), next(it), next(it)
3295 ('1', '3', '5')
3296 >>> it.peek()
3297 '7'
3298 >>> next(it)
3299 '7'
3301 """
3303 # See https://sites.google.com/site/bbayles/index/decorator_factory for
3304 # notes on how this works.
3305 def decorator(*wrapping_args, **wrapping_kwargs):
3306 def outer_wrapper(f):
3307 def inner_wrapper(*args, **kwargs):
3308 result = f(*args, **kwargs)
3309 wrapping_args_ = list(wrapping_args)
3310 wrapping_args_.insert(result_index, result)
3311 return wrapping_func(*wrapping_args_, **wrapping_kwargs)
3313 return inner_wrapper
3315 return outer_wrapper
3317 return decorator
3320def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
3321 """Return a dictionary that maps the items in *iterable* to categories
3322 defined by *keyfunc*, transforms them with *valuefunc*, and
3323 then summarizes them by category with *reducefunc*.
3325 *valuefunc* defaults to the identity function if it is unspecified.
3326 If *reducefunc* is unspecified, no summarization takes place:
3328 >>> keyfunc = lambda x: x.upper()
3329 >>> result = map_reduce('abbccc', keyfunc)
3330 >>> sorted(result.items())
3331 [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])]
3333 Specifying *valuefunc* transforms the categorized items:
3335 >>> keyfunc = lambda x: x.upper()
3336 >>> valuefunc = lambda x: 1
3337 >>> result = map_reduce('abbccc', keyfunc, valuefunc)
3338 >>> sorted(result.items())
3339 [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])]
3341 Specifying *reducefunc* summarizes the categorized items:
3343 >>> keyfunc = lambda x: x.upper()
3344 >>> valuefunc = lambda x: 1
3345 >>> reducefunc = sum
3346 >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc)
3347 >>> sorted(result.items())
3348 [('A', 1), ('B', 2), ('C', 3)]
3350 You may want to filter the input iterable before applying the map/reduce
3351 procedure:
3353 >>> all_items = range(30)
3354 >>> items = [x for x in all_items if 10 <= x <= 20] # Filter
3355 >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1
3356 >>> categories = map_reduce(items, keyfunc=keyfunc)
3357 >>> sorted(categories.items())
3358 [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])]
3359 >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum)
3360 >>> sorted(summaries.items())
3361 [(0, 90), (1, 75)]
3363 Note that all items in the iterable are gathered into a list before the
3364 summarization step, which may require significant storage.
3366 The returned object is a :obj:`collections.defaultdict` with the
3367 ``default_factory`` set to ``None``, such that it behaves like a normal
3368 dictionary.
3370 .. seealso:: :func:`bucket`, :func:`groupby_transform`
3372 If storage is a concern, :func:`bucket` can be used without consuming the
3373 entire iterable right away. If the elements with the same key are already
3374 adjacent, :func:`groupby_transform` or :func:`itertools.groupby` can be
3375 used without any caching overhead.
3377 """
3379 ret = defaultdict(list)
3381 if valuefunc is None:
3382 for item in iterable:
3383 key = keyfunc(item)
3384 ret[key].append(item)
3386 else:
3387 for item in iterable:
3388 key = keyfunc(item)
3389 value = valuefunc(item)
3390 ret[key].append(value)
3392 if reducefunc is not None:
3393 for key, value_list in ret.items():
3394 ret[key] = reducefunc(value_list)
3396 ret.default_factory = None
3397 return ret
3400def rlocate(iterable, pred=bool, window_size=None):
3401 """Yield the index of each item in *iterable* for which *pred* returns
3402 ``True``, starting from the right and moving left.
3404 *pred* defaults to :func:`bool`, which will select truthy items:
3406 >>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4
3407 [4, 2, 1]
3409 Set *pred* to a custom function to, e.g., find the indexes for a particular
3410 item:
3412 >>> iterator = iter('abcb')
3413 >>> pred = lambda x: x == 'b'
3414 >>> list(rlocate(iterator, pred))
3415 [3, 1]
3417 If *window_size* is given, then the *pred* function will be called with
3418 that many items. This enables searching for sub-sequences:
3420 >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
3421 >>> pred = lambda *args: args == (1, 2, 3)
3422 >>> list(rlocate(iterable, pred=pred, window_size=3))
3423 [9, 5, 1]
3425 Beware, this function won't return anything for infinite iterables.
3426 If *iterable* is reversible, ``rlocate`` will reverse it and search from
3427 the right. Otherwise, it will search from the left and return the results
3428 in reverse order.
3430 See :func:`locate` to for other example applications.
3432 """
3433 if window_size is None:
3434 try:
3435 len_iter = len(iterable)
3436 return (len_iter - i - 1 for i in locate(reversed(iterable), pred))
3437 except TypeError:
3438 pass
3440 return reversed(list(locate(iterable, pred, window_size)))
3443def replace(iterable, pred, substitutes, count=None, window_size=1):
3444 """Yield the items from *iterable*, replacing the items for which *pred*
3445 returns ``True`` with the items from the iterable *substitutes*.
3447 >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1]
3448 >>> pred = lambda x: x == 0
3449 >>> substitutes = (2, 3)
3450 >>> list(replace(iterable, pred, substitutes))
3451 [1, 1, 2, 3, 1, 1, 2, 3, 1, 1]
3453 If *count* is given, the number of replacements will be limited:
3455 >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0]
3456 >>> pred = lambda x: x == 0
3457 >>> substitutes = [None]
3458 >>> list(replace(iterable, pred, substitutes, count=2))
3459 [1, 1, None, 1, 1, None, 1, 1, 0]
3461 Use *window_size* to control the number of items passed as arguments to
3462 *pred*. This allows for locating and replacing subsequences.
3464 >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5]
3465 >>> window_size = 3
3466 >>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred
3467 >>> substitutes = [3, 4] # Splice in these items
3468 >>> list(replace(iterable, pred, substitutes, window_size=window_size))
3469 [3, 4, 5, 3, 4, 5]
3471 *pred* may receive fewer than *window_size* arguments at the end of
3472 the iterable and should be able to handle this.
3474 """
3475 if window_size < 1:
3476 raise ValueError('window_size must be at least 1')
3478 # Save the substitutes iterable, since it's used more than once
3479 substitutes = tuple(substitutes)
3481 # Add padding such that the number of windows matches the length of the
3482 # iterable
3483 it = chain(iterable, repeat(_marker, window_size - 1))
3484 windows = windowed(it, window_size)
3486 n = 0
3487 for w in windows:
3488 # Strip any _marker padding so pred never sees internal sentinels.
3489 # Near the end of the iterable, pred will receive fewer arguments.
3490 args = tuple(x for x in w if x is not _marker)
3492 # If the current window matches our predicate (and we haven't hit
3493 # our maximum number of replacements), splice in the substitutes
3494 # and then consume the following windows that overlap with this one.
3495 # For example, if the iterable is (0, 1, 2, 3, 4...)
3496 # and the window size is 2, we have (0, 1), (1, 2), (2, 3)...
3497 # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2)
3498 if args and pred(*args):
3499 if (count is None) or (n < count):
3500 n += 1
3501 yield from substitutes
3502 consume(windows, window_size - 1)
3503 continue
3505 # If there was no match (or we've reached the replacement limit),
3506 # yield the first item from the window.
3507 if args:
3508 yield args[0]
3511def partitions(iterable):
3512 """Yield all possible order-preserving partitions of *iterable*.
3514 >>> iterable = 'abc'
3515 >>> for part in partitions(iterable):
3516 ... print([''.join(p) for p in part])
3517 ['abc']
3518 ['a', 'bc']
3519 ['ab', 'c']
3520 ['a', 'b', 'c']
3522 This is unrelated to :func:`partition`.
3524 """
3525 sequence = list(iterable)
3526 n = len(sequence)
3527 for i in powerset(range(1, n)):
3528 yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]
3531def set_partitions(iterable, k=None, min_size=None, max_size=None):
3532 """
3533 Yield the set partitions of *iterable* into *k* parts. Set partitions are
3534 not order-preserving.
3536 >>> iterable = 'abc'
3537 >>> for part in set_partitions(iterable, 2):
3538 ... print([''.join(p) for p in part])
3539 ['a', 'bc']
3540 ['ab', 'c']
3541 ['b', 'ac']
3544 If *k* is not given, every set partition is generated.
3546 >>> iterable = 'abc'
3547 >>> for part in set_partitions(iterable):
3548 ... print([''.join(p) for p in part])
3549 ['abc']
3550 ['a', 'bc']
3551 ['ab', 'c']
3552 ['b', 'ac']
3553 ['a', 'b', 'c']
3555 if *min_size* and/or *max_size* are given, the minimum and/or maximum size
3556 per block in partition is set.
3558 >>> iterable = 'abc'
3559 >>> for part in set_partitions(iterable, min_size=2):
3560 ... print([''.join(p) for p in part])
3561 ['abc']
3562 >>> for part in set_partitions(iterable, max_size=2):
3563 ... print([''.join(p) for p in part])
3564 ['a', 'bc']
3565 ['ab', 'c']
3566 ['b', 'ac']
3567 ['a', 'b', 'c']
3569 """
3570 L = list(iterable)
3571 n = len(L)
3572 if k is not None:
3573 if k < 1:
3574 raise ValueError(
3575 "Can't partition in a negative or zero number of groups"
3576 )
3577 elif k > n:
3578 return
3580 min_size = min_size if min_size is not None else 0
3581 max_size = max_size if max_size is not None else n
3582 if min_size > max_size:
3583 return
3585 def set_partitions_helper(L, k):
3586 n = len(L)
3587 if k == 1:
3588 yield [L]
3589 elif n == k:
3590 yield [[s] for s in L]
3591 else:
3592 e, *M = L
3593 for p in set_partitions_helper(M, k - 1):
3594 yield [[e], *p]
3595 for p in set_partitions_helper(M, k):
3596 for i in range(len(p)):
3597 yield p[:i] + [[e] + p[i]] + p[i + 1 :]
3599 if k is None:
3600 for k in range(1, n + 1):
3601 yield from filter(
3602 lambda z: all(min_size <= len(bk) <= max_size for bk in z),
3603 set_partitions_helper(L, k),
3604 )
3605 else:
3606 yield from filter(
3607 lambda z: all(min_size <= len(bk) <= max_size for bk in z),
3608 set_partitions_helper(L, k),
3609 )
3612class time_limited:
3613 """
3614 Yield items from *iterable* until *limit_seconds* have passed.
3615 If the time limit expires before all items have been yielded, the
3616 ``timed_out`` parameter will be set to ``True``.
3618 >>> from time import sleep
3619 >>> def generator():
3620 ... yield 1
3621 ... yield 2
3622 ... sleep(0.2)
3623 ... yield 3
3624 >>> iterable = time_limited(0.1, generator())
3625 >>> list(iterable)
3626 [1, 2]
3627 >>> iterable.timed_out
3628 True
3630 Note that the time is checked before each item is yielded, and iteration
3631 stops if the time elapsed is greater than *limit_seconds*. If your time
3632 limit is 1 second, but it takes 2 seconds to generate the first item from
3633 the iterable, the function will run for 2 seconds and not yield anything.
3634 As a special case, when *limit_seconds* is zero, the iterator never
3635 returns anything.
3637 """
3639 def __init__(self, limit_seconds, iterable):
3640 if limit_seconds < 0:
3641 raise ValueError('limit_seconds must be positive')
3642 self.limit_seconds = limit_seconds
3643 self._iterator = iter(iterable)
3644 self._start_time = monotonic()
3645 self.timed_out = False
3647 def __iter__(self):
3648 return self
3650 def __next__(self):
3651 if self.limit_seconds == 0:
3652 self.timed_out = True
3653 raise StopIteration
3654 item = next(self._iterator)
3655 if monotonic() - self._start_time > self.limit_seconds:
3656 self.timed_out = True
3657 raise StopIteration
3659 return item
3662def only(iterable, default=None, too_long=None):
3663 """If *iterable* has only one item, return it.
3664 If it has zero items, return *default*.
3665 If it has more than one item, raise the exception given by *too_long*,
3666 which is ``ValueError`` by default.
3668 >>> only([], default='missing')
3669 'missing'
3670 >>> only([1])
3671 1
3672 >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL
3673 Traceback (most recent call last):
3674 ...
3675 ValueError: Expected exactly one item in iterable, but got 1, 2,
3676 and perhaps more.'
3677 >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL
3678 Traceback (most recent call last):
3679 ...
3680 TypeError
3682 Note that :func:`only` attempts to advance *iterable* twice to ensure there
3683 is only one item. See :func:`spy` or :func:`peekable` to check
3684 iterable contents less destructively.
3686 """
3687 iterator = iter(iterable)
3688 for first in iterator:
3689 for second in iterator:
3690 if too_long is not None:
3691 raise too_long
3692 raise ValueError(
3693 f'Expected exactly one item in iterable, but got {first!r}, '
3694 f'{second!r}, and perhaps more.'
3695 )
3696 return first
3697 return default
3700def ichunked(iterable, n):
3701 """Break *iterable* into sub-iterables with *n* elements each.
3702 :func:`ichunked` is like :func:`chunked`, but it yields iterables
3703 instead of lists.
3705 If the sub-iterables are read in order, the elements of *iterable*
3706 won't be stored in memory.
3707 If they are read out of order, :func:`itertools.tee` is used to cache
3708 elements as necessary.
3710 >>> from itertools import count
3711 >>> all_chunks = ichunked(count(), 4)
3712 >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)
3713 >>> list(c_2) # c_1's elements have been cached; c_3's haven't been
3714 [4, 5, 6, 7]
3715 >>> list(c_1)
3716 [0, 1, 2, 3]
3717 >>> list(c_3)
3718 [8, 9, 10, 11]
3720 """
3721 iterator = iter(iterable)
3722 for first in iterator:
3723 rest = islice(iterator, n - 1)
3724 cache, cacher = tee(rest)
3725 yield chain([first], rest, cache)
3726 consume(cacher)
3729def iequals(*iterables):
3730 """Return ``True`` if all given *iterables* are equal to each other,
3731 which means that they contain the same elements in the same order.
3733 The function is useful for comparing iterables of different data types
3734 or iterables that do not support equality checks.
3736 >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc"))
3737 True
3739 >>> iequals("abc", "acb")
3740 False
3742 Not to be confused with :func:`all_equal`, which checks whether all
3743 elements of iterable are equal to each other.
3745 """
3746 try:
3747 return all(map(all_equal, zip(*iterables, strict=True)))
3748 except ValueError:
3749 return False
3752def distinct_combinations(iterable, r):
3753 """Yield the distinct combinations of *r* items taken from *iterable*.
3755 >>> list(distinct_combinations([0, 0, 1], 2))
3756 [(0, 0), (0, 1)]
3758 Equivalent to ``set(combinations(iterable))``, except duplicates are not
3759 generated and thrown away. For larger input sequences this is much more
3760 efficient.
3762 """
3763 if r < 0:
3764 raise ValueError('r must be non-negative')
3765 elif r == 0:
3766 yield ()
3767 return
3768 pool = tuple(iterable)
3769 generators = [unique_everseen(enumerate(pool), key=itemgetter(1))]
3770 current_combo = [None] * r
3771 level = 0
3772 while generators:
3773 try:
3774 cur_idx, p = next(generators[-1])
3775 except StopIteration:
3776 generators.pop()
3777 level -= 1
3778 continue
3779 current_combo[level] = p
3780 if level + 1 == r:
3781 yield tuple(current_combo)
3782 else:
3783 generators.append(
3784 unique_everseen(
3785 enumerate(pool[cur_idx + 1 :], cur_idx + 1),
3786 key=itemgetter(1),
3787 )
3788 )
3789 level += 1
3792def filter_except(validator, iterable, *exceptions):
3793 """Yield the items from *iterable* for which the *validator* function does
3794 not raise one of the specified *exceptions*.
3796 *validator* is called for each item in *iterable*.
3797 It should be a function that accepts one argument and raises an exception
3798 if that item is not valid.
3800 >>> iterable = ['1', '2', 'three', '4', None]
3801 >>> list(filter_except(int, iterable, ValueError, TypeError))
3802 ['1', '2', '4']
3804 If an exception other than one given by *exceptions* is raised by
3805 *validator*, it is raised like normal.
3806 """
3807 for item in iterable:
3808 try:
3809 validator(item)
3810 except exceptions:
3811 pass
3812 else:
3813 yield item
3816def map_except(function, iterable, *exceptions):
3817 """Transform each item from *iterable* with *function* and yield the
3818 result, unless *function* raises one of the specified *exceptions*.
3820 *function* is called to transform each item in *iterable*.
3821 It should accept one argument.
3823 >>> iterable = ['1', '2', 'three', '4', None]
3824 >>> list(map_except(int, iterable, ValueError, TypeError))
3825 [1, 2, 4]
3827 If an exception other than one given by *exceptions* is raised by
3828 *function*, it is raised like normal.
3829 """
3830 for item in iterable:
3831 try:
3832 yield function(item)
3833 except exceptions:
3834 pass
3837def map_if(iterable, pred, func, func_else=None):
3838 """Evaluate each item from *iterable* using *pred*. If the result is
3839 equivalent to ``True``, transform the item with *func* and yield it.
3840 Otherwise, transform the item with *func_else* and yield it.
3842 *pred*, *func*, and *func_else* should each be functions that accept
3843 one argument. By default, *func_else* is the identity function.
3845 >>> from math import sqrt
3846 >>> iterable = list(range(-5, 5))
3847 >>> iterable
3848 [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
3849 >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))
3850 [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']
3851 >>> list(map_if(iterable, lambda x: x >= 0,
3852 ... lambda x: f'{sqrt(x):.2f}', lambda x: None))
3853 [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00']
3854 """
3856 if func_else is None:
3857 for item in iterable:
3858 yield func(item) if pred(item) else item
3860 else:
3861 for item in iterable:
3862 yield func(item) if pred(item) else func_else(item)
3865def _sample_unweighted(iterator, k, strict):
3866 # Algorithm L in the 1994 paper by Kim-Hung Li:
3867 # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))".
3869 reservoir = list(islice(iterator, k))
3870 if strict and len(reservoir) < k:
3871 raise ValueError('Sample larger than population')
3872 W = 1.0
3874 with suppress(StopIteration):
3875 while True:
3876 W *= random() ** (1 / k)
3877 skip = floor(log(random()) / log1p(-W))
3878 element = next(islice(iterator, skip, None))
3879 reservoir[randrange(k)] = element
3881 shuffle(reservoir)
3882 return reservoir
3885def _sample_weighted(iterator, k, weights, strict):
3886 # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. :
3887 # "Weighted random sampling with a reservoir".
3889 # Log-transform for numerical stability for weights that are small/large
3890 weight_keys = (log(random()) / weight for weight in weights)
3892 # Fill up the reservoir (collection of samples) with the first `k`
3893 # weight-keys and elements, then heapify the list.
3894 reservoir = take(k, zip(weight_keys, iterator))
3895 if strict and len(reservoir) < k:
3896 raise ValueError('Sample larger than population')
3898 heapify(reservoir)
3900 # The number of jumps before changing the reservoir is a random variable
3901 # with an exponential distribution. Sample it using random() and logs.
3902 smallest_weight_key, _ = reservoir[0]
3903 weights_to_skip = log(random()) / smallest_weight_key
3905 for weight, element in zip(weights, iterator):
3906 if weight >= weights_to_skip:
3907 # The notation here is consistent with the paper, but we store
3908 # the weight-keys in log-space for better numerical stability.
3909 smallest_weight_key, _ = reservoir[0]
3910 t_w = exp(weight * smallest_weight_key)
3911 r_2 = uniform(t_w, 1) # generate U(t_w, 1)
3912 weight_key = log(r_2) / weight
3913 heapreplace(reservoir, (weight_key, element))
3914 smallest_weight_key, _ = reservoir[0]
3915 weights_to_skip = log(random()) / smallest_weight_key
3916 else:
3917 weights_to_skip -= weight
3919 ret = [element for weight_key, element in reservoir]
3920 shuffle(ret)
3921 return ret
3924def _sample_counted(population, k, counts, strict):
3925 element = None
3926 remaining = 0
3928 def feed(i):
3929 # Advance *i* steps ahead and consume an element
3930 nonlocal element, remaining
3932 while i + 1 > remaining:
3933 i = i - remaining
3934 element = next(population)
3935 remaining = next(counts)
3936 remaining -= i + 1
3937 return element
3939 with suppress(StopIteration):
3940 reservoir = []
3941 for _ in range(k):
3942 reservoir.append(feed(0))
3944 if strict and len(reservoir) < k:
3945 raise ValueError('Sample larger than population')
3947 with suppress(StopIteration):
3948 W = 1.0
3949 while True:
3950 W *= random() ** (1 / k)
3951 skip = floor(log(random()) / log1p(-W))
3952 element = feed(skip)
3953 reservoir[randrange(k)] = element
3955 shuffle(reservoir)
3956 return reservoir
3959def sample(iterable, k, weights=None, *, counts=None, strict=False):
3960 """Return a *k*-length list of elements chosen (without replacement)
3961 from the *iterable*.
3963 Similar to :func:`random.sample`, but works on inputs that aren't
3964 indexable (such as sets and dictionaries) and on inputs where the
3965 size isn't known in advance (such as generators).
3967 >>> iterable = range(100)
3968 >>> sample(iterable, 5) # doctest: +SKIP
3969 [81, 60, 96, 16, 4]
3971 For iterables with repeated elements, you may supply *counts* to
3972 indicate the repeats.
3974 >>> iterable = ['a', 'b']
3975 >>> counts = [3, 4] # Equivalent to 'a', 'a', 'a', 'b', 'b', 'b', 'b'
3976 >>> sample(iterable, k=3, counts=counts) # doctest: +SKIP
3977 ['a', 'a', 'b']
3979 An iterable with *weights* may be given:
3981 >>> iterable = range(100)
3982 >>> weights = (i * i + 1 for i in range(100))
3983 >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP
3984 [79, 67, 74, 66, 78]
3986 Weighted selections are made without replacement.
3987 After an element is selected, it is removed from the pool and the
3988 relative weights of the other elements increase (this
3989 does not match the behavior of :func:`random.sample`'s *counts*
3990 parameter). Note that *weights* may not be used with *counts*.
3992 If the length of *iterable* is less than *k*,
3993 ``ValueError`` is raised if *strict* is ``True`` and
3994 all elements are returned (in shuffled order) if *strict* is ``False``.
3996 By default, the `Algorithm L <https://w.wiki/ANrM>`__ reservoir sampling
3997 technique is used. When *weights* are provided,
3998 `Algorithm A-ExpJ <https://w.wiki/ANrS>`__ is used instead.
4000 Notes on reproducibility:
4002 * The algorithms rely on inexact floating-point functions provided
4003 by the underlying math library (e.g. ``log``, ``log1p``, and ``pow``).
4004 Those functions can `produce slightly different results
4005 <https://members.loria.fr/PZimmermann/papers/accuracy.pdf>`_ on
4006 different builds. Accordingly, selections can vary across builds
4007 even for the same seed.
4009 * The algorithms loop over the input and make selections based on
4010 ordinal position, so selections from unordered collections (such as
4011 sets) won't reproduce across sessions on the same platform using the
4012 same seed. For example, this won't reproduce::
4014 >> seed(8675309)
4015 >> sample(set('abcdefghijklmnopqrstuvwxyz'), 10)
4016 ['c', 'p', 'e', 'w', 's', 'a', 'j', 'd', 'n', 't']
4018 """
4019 iterator = iter(iterable)
4021 if k < 0:
4022 raise ValueError('k must be non-negative')
4024 if k == 0:
4025 return []
4027 if weights is not None and counts is not None:
4028 raise TypeError('weights and counts are mutually exclusive')
4030 elif weights is not None:
4031 weights = iter(weights)
4032 return _sample_weighted(iterator, k, weights, strict)
4034 elif counts is not None:
4035 counts = iter(counts)
4036 return _sample_counted(iterator, k, counts, strict)
4038 else:
4039 return _sample_unweighted(iterator, k, strict)
4042def is_sorted(iterable, key=None, reverse=False, strict=False):
4043 """Returns ``True`` if the items of iterable are in sorted order, and
4044 ``False`` otherwise. *key* and *reverse* have the same meaning that they do
4045 in the built-in :func:`sorted` function.
4047 >>> is_sorted(['1', '2', '3', '4', '5'], key=int)
4048 True
4049 >>> is_sorted([5, 4, 3, 1, 2], reverse=True)
4050 False
4052 If *strict*, tests for strict sorting, that is, returns ``False`` if equal
4053 elements are found:
4055 >>> is_sorted([1, 2, 2])
4056 True
4057 >>> is_sorted([1, 2, 2], strict=True)
4058 False
4060 The function returns ``False`` after encountering the first out-of-order
4061 item, which means it may produce results that differ from the built-in
4062 :func:`sorted` function for objects with unusual comparison dynamics
4063 (like ``math.nan``). If there are no out-of-order items, the iterable is
4064 exhausted.
4065 """
4066 it = iterable if (key is None) else map(key, iterable)
4067 a, b = tee(it)
4068 next(b, None)
4069 if reverse:
4070 b, a = a, b
4071 return all(map(lt, a, b)) if strict else not any(map(lt, b, a))
4074class AbortThread(BaseException):
4075 pass
4078class callback_iter:
4079 """Convert a function that uses callbacks to an iterator.
4081 .. deprecated:: 11.0.0
4082 Will be removed in a future major release.
4084 Let *func* be a function that takes a `callback` keyword argument.
4085 For example:
4087 >>> def func(callback=None):
4088 ... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:
4089 ... if callback:
4090 ... callback(i, c)
4091 ... return 4
4094 Use ``with callback_iter(func)`` to get an iterator over the parameters
4095 that are delivered to the callback.
4097 >>> with callback_iter(func) as it:
4098 ... for args, kwargs in it:
4099 ... print(args)
4100 (1, 'a')
4101 (2, 'b')
4102 (3, 'c')
4104 The function will be called in a background thread. The ``done`` property
4105 indicates whether it has completed execution.
4107 >>> it.done
4108 True
4110 If it completes successfully, its return value will be available
4111 in the ``result`` property.
4113 >>> it.result
4114 4
4116 Notes:
4118 * If the function uses some keyword argument besides ``callback``, supply
4119 *callback_kwd*.
4120 * If it finished executing, but raised an exception, accessing the
4121 ``result`` property will raise the same exception.
4122 * If it hasn't finished executing, accessing the ``result``
4123 property from within the ``with`` block will raise ``RuntimeError``.
4124 * If it hasn't finished executing, accessing the ``result`` property from
4125 outside the ``with`` block will raise a
4126 ``more_itertools.AbortThread`` exception.
4127 * Provide *wait_seconds* to adjust how frequently the it is polled for
4128 output.
4130 """
4132 def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):
4133 self._func = func
4134 self._callback_kwd = callback_kwd
4135 self._aborted = False
4136 self._future = None
4137 self._wait_seconds = wait_seconds
4139 # Lazily import concurrent.future
4140 self._module = __import__('concurrent.futures').futures
4141 self._executor = self._module.ThreadPoolExecutor(max_workers=1)
4142 self._iterator = self._reader()
4144 def __enter__(self):
4145 return self
4147 def __exit__(self, exc_type, exc_value, traceback):
4148 self._aborted = True
4149 self._executor.shutdown()
4151 def __iter__(self):
4152 return self
4154 def __next__(self):
4155 return next(self._iterator)
4157 @property
4158 def done(self):
4159 if self._future is None:
4160 return False
4161 return self._future.done()
4163 @property
4164 def result(self):
4165 if self._future:
4166 try:
4167 return self._future.result(timeout=0)
4168 except self._module.TimeoutError:
4169 pass
4171 raise RuntimeError('Function has not yet completed')
4173 def _reader(self):
4174 q = Queue()
4176 def callback(*args, **kwargs):
4177 if self._aborted:
4178 raise AbortThread('canceled by user')
4180 q.put((args, kwargs))
4182 self._future = self._executor.submit(
4183 self._func, **{self._callback_kwd: callback}
4184 )
4186 while True:
4187 try:
4188 item = q.get(timeout=self._wait_seconds)
4189 except Empty:
4190 pass
4191 else:
4192 q.task_done()
4193 yield item
4195 if self._future.done():
4196 break
4198 remaining = []
4199 while True:
4200 try:
4201 item = q.get_nowait()
4202 except Empty:
4203 break
4204 else:
4205 q.task_done()
4206 remaining.append(item)
4207 q.join()
4208 yield from remaining
4211def windowed_complete(iterable, n):
4212 """
4213 Yield ``(beginning, middle, end)`` tuples, where:
4215 * Each ``middle`` has *n* items from *iterable*
4216 * Each ``beginning`` has the items before the ones in ``middle``
4217 * Each ``end`` has the items after the ones in ``middle``
4219 >>> iterable = range(7)
4220 >>> n = 3
4221 >>> for beginning, middle, end in windowed_complete(iterable, n):
4222 ... print(beginning, middle, end)
4223 () (0, 1, 2) (3, 4, 5, 6)
4224 (0,) (1, 2, 3) (4, 5, 6)
4225 (0, 1) (2, 3, 4) (5, 6)
4226 (0, 1, 2) (3, 4, 5) (6,)
4227 (0, 1, 2, 3) (4, 5, 6) ()
4229 Note that *n* must be at least 0 and most equal to the length of
4230 *iterable*.
4232 This function will exhaust the iterable and may require significant
4233 storage.
4234 """
4235 if n < 0:
4236 raise ValueError('n must be >= 0')
4238 seq = tuple(iterable)
4239 size = len(seq)
4241 if n > size:
4242 raise ValueError('n must be <= len(seq)')
4244 for i in range(size - n + 1):
4245 beginning = seq[:i]
4246 middle = seq[i : i + n]
4247 end = seq[i + n :]
4248 yield beginning, middle, end
4251def all_unique(iterable, key=None):
4252 """
4253 Returns ``True`` if all the elements of *iterable* are unique (no two
4254 elements are equal).
4256 >>> all_unique('ABCB')
4257 False
4259 If a *key* function is specified, it will be used to make comparisons.
4261 >>> all_unique('ABCb')
4262 True
4263 >>> all_unique('ABCb', str.lower)
4264 False
4266 The function returns as soon as the first non-unique element is
4267 encountered. Iterables with a mix of hashable and unhashable items can
4268 be used, but the function will be slower for unhashable items.
4269 """
4270 seenset = set()
4271 seenset_add = seenset.add
4272 seenlist = []
4273 seenlist_add = seenlist.append
4274 for element in map(key, iterable) if key else iterable:
4275 try:
4276 if element in seenset:
4277 return False
4278 seenset_add(element)
4279 except TypeError:
4280 if element in seenlist:
4281 return False
4282 seenlist_add(element)
4283 return True
4286def nth_product(index, *iterables, repeat=1):
4287 """Equivalent to ``list(product(*iterables, repeat=repeat))[index]``.
4289 The products of *iterables* can be ordered lexicographically.
4290 :func:`nth_product` computes the product at sort position *index* without
4291 computing the previous products.
4293 >>> nth_product(8, range(2), range(2), range(2), range(2))
4294 (1, 0, 0, 0)
4296 The *repeat* keyword argument specifies the number of repetitions
4297 of the iterables. The above example is equivalent to::
4299 >>> nth_product(8, range(2), repeat=4)
4300 (1, 0, 0, 0)
4302 ``IndexError`` will be raised if the given *index* is invalid.
4303 """
4304 pools = tuple(map(tuple, reversed(iterables))) * repeat
4305 ns = tuple(map(len, pools))
4307 c = prod(ns)
4309 if index < 0:
4310 index += c
4311 if not 0 <= index < c:
4312 raise IndexError
4314 result = []
4315 for pool, n in zip(pools, ns):
4316 result.append(pool[index % n])
4317 index //= n
4319 return tuple(reversed(result))
4322def nth_permutation(iterable, r, index):
4323 """Equivalent to ``list(permutations(iterable, r))[index]```
4325 The subsequences of *iterable* that are of length *r* where order is
4326 important can be ordered lexicographically. :func:`nth_permutation`
4327 computes the subsequence at sort position *index* directly, without
4328 computing the previous subsequences.
4330 >>> nth_permutation('ghijk', 2, 5)
4331 ('h', 'i')
4333 ``ValueError`` will be raised If *r* is negative.
4334 ``IndexError`` will be raised if the given *index* is invalid.
4335 """
4336 pool = list(iterable)
4337 n = len(pool)
4338 if r is None:
4339 r = n
4340 c = perm(n, r)
4342 if index < 0:
4343 index += c
4344 if not 0 <= index < c:
4345 raise IndexError
4347 result = [0] * r
4348 q = index
4349 for d in range(n - r + 1, n + 1):
4350 q, i = divmod(q, d)
4351 result[n - d] = i
4352 if q == 0:
4353 break
4355 return tuple(map(pool.pop, result))
4358def nth_combination_with_replacement(iterable, r, index):
4359 """Equivalent to
4360 ``list(combinations_with_replacement(iterable, r))[index]``.
4363 The subsequences with repetition of *iterable* that are of length *r* can
4364 be ordered lexicographically. :func:`nth_combination_with_replacement`
4365 computes the subsequence at sort position *index* directly, without
4366 computing the previous subsequences with replacement.
4368 >>> nth_combination_with_replacement(range(5), 3, 5)
4369 (0, 1, 1)
4371 ``ValueError`` will be raised If *r* is negative.
4372 ``IndexError`` will be raised if the given *index* is invalid.
4373 """
4374 pool = tuple(iterable)
4375 n = len(pool)
4376 if r < 0:
4377 raise ValueError
4378 c = comb(n + r - 1, r) if n else 0 if r else 1
4380 if index < 0:
4381 index += c
4382 if not 0 <= index < c:
4383 raise IndexError
4385 result = []
4386 i = 0
4387 while r:
4388 r -= 1
4389 while n >= 0:
4390 num_combs = comb(n + r - 1, r)
4391 if index < num_combs:
4392 break
4393 n -= 1
4394 i += 1
4395 index -= num_combs
4396 result.append(pool[i])
4398 return tuple(result)
4401def value_chain(*args):
4402 """Yield all arguments passed to the function in the same order in which
4403 they were passed. If an argument itself is iterable then iterate over its
4404 values.
4406 >>> list(value_chain(1, 2, 3, [4, 5, 6]))
4407 [1, 2, 3, 4, 5, 6]
4409 Binary and text strings are not considered iterable and are emitted
4410 as-is:
4412 >>> list(value_chain('12', '34', ['56', '78']))
4413 ['12', '34', '56', '78']
4415 Pre- or postpend a single element to an iterable:
4417 >>> list(value_chain(1, [2, 3, 4, 5, 6]))
4418 [1, 2, 3, 4, 5, 6]
4419 >>> list(value_chain([1, 2, 3, 4, 5], 6))
4420 [1, 2, 3, 4, 5, 6]
4422 Multiple levels of nesting are not flattened.
4424 """
4425 scalar_types = (str, bytes)
4426 for value in args:
4427 if isinstance(value, scalar_types):
4428 yield value
4429 continue
4430 try:
4431 it = iter(value)
4432 except TypeError:
4433 yield value
4434 else:
4435 yield from it
4438def product_index(element, *iterables, repeat=1):
4439 """Equivalent to ``list(product(*iterables, repeat=repeat)).index(tuple(element))``
4441 The products of *iterables* can be ordered lexicographically.
4442 :func:`product_index` computes the first index of *element* without
4443 computing the previous products.
4445 >>> product_index([8, 2], range(10), range(5))
4446 42
4448 The *repeat* keyword argument specifies the number of repetitions
4449 of the iterables::
4451 >>> product_index([8, 0, 7], range(10), repeat=3)
4452 807
4454 ``ValueError`` will be raised if the given *element* isn't in the product
4455 of *args*.
4456 """
4457 elements = tuple(element)
4458 pools = tuple(map(tuple, iterables)) * repeat
4459 if len(elements) != len(pools):
4460 raise ValueError('element is not a product of args')
4462 index = 0
4463 for elem, pool in zip(elements, pools):
4464 index = index * len(pool) + pool.index(elem)
4465 return index
4468def combination_index(element, iterable):
4469 """Equivalent to ``list(combinations(iterable, r)).index(element)``
4471 The subsequences of *iterable* that are of length *r* can be ordered
4472 lexicographically. :func:`combination_index` computes the index of the
4473 first *element*, without computing the previous combinations.
4475 >>> combination_index('adf', 'abcdefg')
4476 10
4478 ``ValueError`` will be raised if the given *element* isn't one of the
4479 combinations of *iterable*.
4480 """
4481 element = enumerate(element)
4482 k, y = next(element, (None, None))
4483 if k is None:
4484 return 0
4486 indexes = []
4487 pool = enumerate(iterable)
4488 for n, x in pool:
4489 if x == y:
4490 indexes.append(n)
4491 tmp, y = next(element, (None, None))
4492 if tmp is None:
4493 break
4494 else:
4495 k = tmp
4496 else:
4497 raise ValueError('element is not a combination of iterable')
4499 n, _ = last(pool, default=(n, None))
4501 index = 1
4502 for i, j in enumerate(reversed(indexes), start=1):
4503 j = n - j
4504 if i <= j:
4505 index += comb(j, i)
4507 return comb(n + 1, k + 1) - index
4510def combination_with_replacement_index(element, iterable):
4511 """Equivalent to
4512 ``list(combinations_with_replacement(iterable, r)).index(element)``
4514 The subsequences with repetition of *iterable* that are of length *r* can
4515 be ordered lexicographically. :func:`combination_with_replacement_index`
4516 computes the index of the first *element*, without computing the previous
4517 combinations with replacement.
4519 >>> combination_with_replacement_index('adf', 'abcdefg')
4520 20
4522 ``ValueError`` will be raised if the given *element* isn't one of the
4523 combinations with replacement of *iterable*.
4524 """
4525 element = tuple(element)
4526 r = len(element)
4527 pool = tuple(iterable)
4528 n = len(pool)
4530 occupations = [0] * n
4531 try:
4532 i = 0
4533 for e in element:
4534 i = pool.index(e, i)
4535 occupations[i] += 1
4536 except ValueError:
4537 raise ValueError(
4538 'element is not a combination with replacement of iterable'
4539 )
4541 index = 0
4542 cumulative_sum = 0
4543 for k in range(1, n):
4544 cumulative_sum += occupations[k - 1]
4545 j = (r - cumulative_sum) + (n - k) - 1
4546 i = n - k
4547 if i <= j:
4548 index += comb(j, i)
4550 return index
4553def permutation_index(element, iterable):
4554 """Equivalent to ``list(permutations(iterable, r)).index(element)```
4556 The subsequences of *iterable* that are of length *r* where order is
4557 important can be ordered lexicographically. :func:`permutation_index`
4558 computes the index of the first *element* directly, without computing
4559 the previous permutations.
4561 >>> permutation_index([1, 3, 2], range(5))
4562 19
4564 ``ValueError`` will be raised if the given *element* isn't one of the
4565 permutations of *iterable*.
4566 """
4567 index = 0
4568 pool = list(iterable)
4569 for i, x in zip(range(len(pool), -1, -1), element):
4570 r = pool.index(x)
4571 index = index * i + r
4572 del pool[r]
4574 return index
4577class countable:
4578 """Wrap *iterable* and keep a count of how many items have been consumed.
4580 The ``items_seen`` attribute starts at ``0`` and increments as the iterable
4581 is consumed:
4583 >>> iterable = map(str, range(10))
4584 >>> it = countable(iterable)
4585 >>> it.items_seen
4586 0
4587 >>> next(it), next(it)
4588 ('0', '1')
4589 >>> list(it)
4590 ['2', '3', '4', '5', '6', '7', '8', '9']
4591 >>> it.items_seen
4592 10
4593 """
4595 def __init__(self, iterable):
4596 self._iterator = iter(iterable)
4597 self.items_seen = 0
4599 def __iter__(self):
4600 return self
4602 def __next__(self):
4603 item = next(self._iterator)
4604 self.items_seen += 1
4606 return item
4609def chunked_even(iterable, n):
4610 """Break *iterable* into lists of approximately length *n*.
4611 Items are distributed such the lengths of the lists differ by at most
4612 1 item.
4614 >>> iterable = [1, 2, 3, 4, 5, 6, 7]
4615 >>> n = 3
4616 >>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2
4617 [[1, 2, 3], [4, 5], [6, 7]]
4618 >>> list(chunked(iterable, n)) # List lengths: 3, 3, 1
4619 [[1, 2, 3], [4, 5, 6], [7]]
4621 """
4622 iterator = iter(iterable)
4624 # Initialize a buffer to process the chunks while keeping
4625 # some back to fill any underfilled chunks
4626 min_buffer = (n - 1) * (n - 2)
4627 buffer = list(islice(iterator, min_buffer))
4629 # Append items until we have a completed chunk
4630 for _ in islice(map(buffer.append, iterator), n, None, n):
4631 yield buffer[:n]
4632 del buffer[:n]
4634 # Check if any chunks need addition processing
4635 if not buffer:
4636 return
4637 length = len(buffer)
4639 # Chunks are either size `full_size <= n` or `partial_size = full_size - 1`
4640 q, r = divmod(length, n)
4641 num_lists = q + (1 if r > 0 else 0)
4642 q, r = divmod(length, num_lists)
4643 full_size = q + (1 if r > 0 else 0)
4644 partial_size = full_size - 1
4645 num_full = length - partial_size * num_lists
4647 # Yield chunks of full size
4648 partial_start_idx = num_full * full_size
4649 if full_size > 0:
4650 for i in range(0, partial_start_idx, full_size):
4651 yield buffer[i : i + full_size]
4653 # Yield chunks of partial size
4654 if partial_size > 0:
4655 for i in range(partial_start_idx, length, partial_size):
4656 yield buffer[i : i + partial_size]
4659def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False):
4660 """A version of :func:`zip` that "broadcasts" any scalar
4661 (i.e., non-iterable) items into output tuples.
4663 >>> iterable_1 = [1, 2, 3]
4664 >>> iterable_2 = ['a', 'b', 'c']
4665 >>> scalar = '_'
4666 >>> list(zip_broadcast(iterable_1, iterable_2, scalar))
4667 [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')]
4669 The *scalar_types* keyword argument determines what types are considered
4670 scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to
4671 treat strings and byte strings as iterable:
4673 >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None))
4674 [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')]
4676 If the *strict* keyword argument is ``True``, then
4677 ``ValueError`` will be raised if any of the iterables have
4678 different lengths.
4679 """
4681 def get_iterator(obj):
4682 if scalar_types and isinstance(obj, scalar_types):
4683 return None
4684 try:
4685 return iter(obj)
4686 except TypeError:
4687 return None
4689 size = len(objects)
4690 if not size:
4691 return
4693 new_item = [None] * size
4694 iterables, iterable_positions = [], []
4695 for i, obj in enumerate(objects):
4696 iterator = get_iterator(obj)
4697 if iterator is None:
4698 new_item[i] = obj
4699 else:
4700 iterables.append(iterator)
4701 iterable_positions.append(i)
4703 if not iterables:
4704 yield tuple(objects)
4705 return
4707 for item in zip(*iterables, strict=strict):
4708 for i, new_item[i] in zip(iterable_positions, item):
4709 pass
4710 yield tuple(new_item)
4713def unique_in_window(iterable, n, key=None):
4714 """Yield the items from *iterable* that haven't been seen recently.
4715 *n* is the size of the sliding window.
4717 >>> iterable = [0, 1, 0, 2, 3, 0]
4718 >>> n = 3
4719 >>> list(unique_in_window(iterable, n))
4720 [0, 1, 2, 3, 0]
4722 The *key* function, if provided, will be used to determine uniqueness:
4724 >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower()))
4725 ['a', 'b', 'c', 'd', 'a']
4727 Updates a sliding window no larger than n and yields a value
4728 if the item only occurs once in the updated window.
4730 When `n == 1`, *unique_in_window* is memoryless:
4732 >>> list(unique_in_window('aab', n=1))
4733 ['a', 'a', 'b']
4735 The items in *iterable* must be hashable.
4737 """
4738 if n <= 0:
4739 raise ValueError('n must be greater than 0')
4741 window = deque(maxlen=n)
4742 counts = Counter()
4743 use_key = key is not None
4745 for item in iterable:
4746 if len(window) == n:
4747 to_discard = window[0]
4748 if counts[to_discard] == 1:
4749 del counts[to_discard]
4750 else:
4751 counts[to_discard] -= 1
4753 k = key(item) if use_key else item
4754 if k not in counts:
4755 yield item
4756 counts[k] += 1
4757 window.append(k)
4760def duplicates_everseen(iterable, key=None):
4761 """Yield duplicate elements after their first appearance.
4763 >>> list(duplicates_everseen('mississippi'))
4764 ['s', 'i', 's', 's', 'i', 'p', 'i']
4765 >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower))
4766 ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a']
4768 This function is analogous to :func:`unique_everseen` and is subject to
4769 the same performance considerations.
4771 If you would like each duplicate to only appear once, much like ``uniq -d``
4772 in the Unix shell or ``Itertools::duplicates`` from the Rust ``itertools``
4773 crate, pass the return value of this function into :func:`unique_everseen`
4774 with the same ``key``.
4776 """
4777 seen_set = set()
4778 seen_list = []
4779 use_key = key is not None
4781 for element in iterable:
4782 k = key(element) if use_key else element
4783 try:
4784 if k not in seen_set:
4785 seen_set.add(k)
4786 else:
4787 yield element
4788 except TypeError:
4789 if k not in seen_list:
4790 seen_list.append(k)
4791 else:
4792 yield element
4795def duplicates_justseen(iterable, key=None):
4796 """Yields serially-duplicate elements after their first appearance.
4798 >>> list(duplicates_justseen('mississippi'))
4799 ['s', 's', 'p']
4800 >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower))
4801 ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a']
4803 This function is analogous to :func:`unique_justseen`.
4805 """
4806 return flatten(g for _, g in groupby(iterable, key) for _ in g)
4809def classify_unique(iterable, key=None):
4810 """Classify each element in terms of its uniqueness.
4812 For each element in the input iterable, return a 3-tuple consisting of:
4814 1. The element itself
4815 2. ``False`` if the element is equal to the one preceding it in the input,
4816 ``True`` otherwise (i.e. the equivalent of :func:`unique_justseen`)
4817 3. ``False`` if this element has been seen anywhere in the input before,
4818 ``True`` otherwise (i.e. the equivalent of :func:`unique_everseen`)
4820 >>> list(classify_unique('otto')) # doctest: +NORMALIZE_WHITESPACE
4821 [('o', True, True),
4822 ('t', True, True),
4823 ('t', False, False),
4824 ('o', True, False)]
4826 This function is analogous to :func:`unique_everseen` and is subject to
4827 the same performance considerations.
4829 """
4830 seen_set = set()
4831 seen_list = []
4832 use_key = key is not None
4833 previous = None
4835 for i, element in enumerate(iterable):
4836 k = key(element) if use_key else element
4837 is_unique_justseen = not i or previous != k
4838 previous = k
4839 is_unique_everseen = False
4840 try:
4841 if k not in seen_set:
4842 seen_set.add(k)
4843 is_unique_everseen = True
4844 except TypeError:
4845 if k not in seen_list:
4846 seen_list.append(k)
4847 is_unique_everseen = True
4848 yield element, is_unique_justseen, is_unique_everseen
4851def minmax(iterable_or_value, *others, key=None, default=_marker):
4852 """Returns both the smallest and largest items from an iterable
4853 or from two or more arguments.
4855 >>> minmax([3, 1, 5])
4856 (1, 5)
4858 >>> minmax(4, 2, 6)
4859 (2, 6)
4861 If a *key* function is provided, it will be used to transform the input
4862 items for comparison.
4864 >>> minmax([5, 30], key=str) # '30' sorts before '5'
4865 (30, 5)
4867 If a *default* value is provided, it will be returned if there are no
4868 input items.
4870 >>> minmax([], default=(0, 0))
4871 (0, 0)
4873 Otherwise ``ValueError`` is raised.
4875 This function makes a single pass over the input elements and takes care to
4876 minimize the number of comparisons made during processing.
4878 Note that unlike the builtin ``max`` function, which always returns the first
4879 item with the maximum value, this function may return another item when there are
4880 ties.
4882 This function is based on the
4883 `recipe <https://code.activestate.com/recipes/577916-fast-minmax-function>`__ by
4884 Raymond Hettinger.
4885 """
4886 iterable = (iterable_or_value, *others) if others else iterable_or_value
4888 it = iter(iterable)
4890 try:
4891 lo = hi = next(it)
4892 except StopIteration as exc:
4893 if default is _marker:
4894 raise ValueError(
4895 '`minmax()` argument is an empty iterable. '
4896 'Provide a `default` value to suppress this error.'
4897 ) from exc
4898 return default
4900 # Different branches depending on the presence of key. This saves a lot
4901 # of unimportant copies which would slow the "key=None" branch
4902 # significantly down.
4903 if key is None:
4904 for x, y in zip_longest(it, it, fillvalue=lo):
4905 if y < x:
4906 if y < lo:
4907 lo = y
4908 if hi < x:
4909 hi = x
4910 else:
4911 if x < lo:
4912 lo = x
4913 if hi < y:
4914 hi = y
4916 else:
4917 lo_key = hi_key = key(lo)
4919 for x, y in zip_longest(it, it, fillvalue=lo):
4920 x_key, y_key = key(x), key(y)
4922 if y_key < x_key:
4923 if y_key < lo_key:
4924 lo, lo_key = y, y_key
4925 if hi_key < x_key:
4926 hi, hi_key = x, x_key
4927 else:
4928 if x_key < lo_key:
4929 lo, lo_key = x, x_key
4930 if hi_key < y_key:
4931 hi, hi_key = y, y_key
4933 return lo, hi
4936def constrained_batches(
4937 iterable, max_size, max_count=None, get_len=len, strict=True
4938):
4939 """Yield batches of items from *iterable* with a combined size limited by
4940 *max_size*.
4942 >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
4943 >>> list(constrained_batches(iterable, 10))
4944 [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')]
4946 If a *max_count* is supplied, the number of items per batch is also
4947 limited. It must be greater than zero:
4949 >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
4950 >>> list(constrained_batches(iterable, 10, max_count = 2))
4951 [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)]
4953 If a *get_len* function is supplied, use that instead of :func:`len` to
4954 determine item size.
4956 If *strict* is ``True``, raise ``ValueError`` if any single item is bigger
4957 than *max_size*. Otherwise, allow single items to exceed *max_size*.
4958 """
4959 if max_size <= 0:
4960 raise ValueError('maximum size must be greater than zero')
4961 if max_count is not None and max_count <= 0:
4962 raise ValueError('maximum count must be greater than zero')
4964 batch = []
4965 batch_size = 0
4966 batch_count = 0
4967 for item in iterable:
4968 item_len = get_len(item)
4969 if strict and item_len > max_size:
4970 raise ValueError('item size exceeds maximum size')
4972 reached_count = batch_count == max_count
4973 reached_size = item_len + batch_size > max_size
4974 if batch_count and (reached_size or reached_count):
4975 yield tuple(batch)
4976 batch.clear()
4977 batch_size = 0
4978 batch_count = 0
4980 batch.append(item)
4981 batch_size += item_len
4982 batch_count += 1
4984 if batch:
4985 yield tuple(batch)
4988def gray_product(*iterables, repeat=1):
4989 """Like :func:`itertools.product`, but return tuples in an order such
4990 that only one element in the generated tuple changes from one iteration
4991 to the next.
4993 >>> list(gray_product('AB','CD'))
4994 [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')]
4996 The *repeat* keyword argument specifies the number of repetitions
4997 of the iterables. For example, ``gray_product('AB', repeat=3)`` is
4998 equivalent to ``gray_product('AB', 'AB', 'AB')``.
5000 This function consumes all of the input iterables before producing output.
5001 If any of the input iterables have fewer than two items, ``ValueError``
5002 is raised.
5004 For information on the algorithm, see
5005 `this section <https://www-cs-faculty.stanford.edu/~knuth/fasc2a.ps.gz>`__
5006 of Donald Knuth's *The Art of Computer Programming*.
5007 """
5008 all_iterables = tuple(map(tuple, iterables)) * repeat
5009 iterable_count = len(all_iterables)
5010 for iterable in all_iterables:
5011 if len(iterable) < 2:
5012 raise ValueError("each iterable must have two or more items")
5014 # This is based on "Algorithm H" from section 7.2.1.1, page 20.
5015 # a holds the indexes of the source iterables for the n-tuple to be yielded
5016 # f is the array of "focus pointers"
5017 # o is the array of "directions"
5018 a = [0] * iterable_count
5019 f = list(range(iterable_count + 1))
5020 o = [1] * iterable_count
5021 while True:
5022 yield tuple(all_iterables[i][a[i]] for i in range(iterable_count))
5023 j = f[0]
5024 f[0] = 0
5025 if j == iterable_count:
5026 break
5027 a[j] = a[j] + o[j]
5028 if a[j] == 0 or a[j] == len(all_iterables[j]) - 1:
5029 o[j] = -o[j]
5030 f[j] = f[j + 1]
5031 f[j + 1] = j + 1
5034def partial_product(*iterables, repeat=1):
5035 """Yields tuples containing one item from each iterator, with subsequent
5036 tuples changing a single item at a time by advancing each iterator until it
5037 is exhausted. This sequence guarantees every value in each iterable is
5038 output at least once without generating all possible combinations.
5040 This may be useful, for example, when testing an expensive function.
5042 >>> list(partial_product('AB', 'C', 'DEF'))
5043 [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')]
5045 The *repeat* keyword argument specifies the number of repetitions
5046 of the iterables. For example, ``partial_product('AB', repeat=3)`` is
5047 equivalent to ``partial_product('AB', 'AB', 'AB')``.
5048 """
5050 all_iterables = tuple(map(tuple, iterables)) * repeat
5051 iterators = tuple(map(iter, all_iterables))
5053 try:
5054 prod = [next(it) for it in iterators]
5055 except StopIteration:
5056 return
5057 yield tuple(prod)
5059 for i, it in enumerate(iterators):
5060 for prod[i] in it:
5061 yield tuple(prod)
5064def takewhile_inclusive(predicate, iterable):
5065 """A variant of :func:`takewhile` that yields one additional element.
5067 >>> list(takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1]))
5068 [1, 4, 6]
5070 :func:`takewhile` would return ``[1, 4]``.
5071 """
5072 for x in iterable:
5073 yield x
5074 if not predicate(x):
5075 break
5078def outer_product(func, xs, ys, *args, **kwargs):
5079 """A generalized outer product that applies a binary function to all
5080 pairs of items. Returns a 2D matrix with ``len(xs)`` rows and ``len(ys)``
5081 columns.
5082 Also accepts ``*args`` and ``**kwargs`` that are passed to ``func``.
5084 Multiplication table:
5086 >>> from operator import mul
5087 >>> list(outer_product(mul, range(1, 4), range(1, 6)))
5088 [(1, 2, 3, 4, 5), (2, 4, 6, 8, 10), (3, 6, 9, 12, 15)]
5090 Cross tabulation:
5092 >>> xs = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']
5093 >>> ys = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z']
5094 >>> pair_counts = Counter(zip(xs, ys))
5095 >>> count_rows = lambda x, y: pair_counts[x, y]
5096 >>> list(outer_product(count_rows, sorted(set(xs)), sorted(set(ys))))
5097 [(2, 3, 0), (1, 0, 4)]
5099 Usage with ``*args`` and ``**kwargs``:
5101 >>> animals = ['cat', 'wolf', 'mouse']
5102 >>> list(outer_product(min, animals, animals, key=len))
5103 [('cat', 'cat', 'cat'), ('cat', 'wolf', 'wolf'), ('cat', 'wolf', 'mouse')]
5104 """
5105 ys = tuple(ys)
5106 return batched(
5107 starmap(lambda x, y: func(x, y, *args, **kwargs), product(xs, ys)),
5108 n=len(ys),
5109 )
5112def iter_suppress(iterable, *exceptions):
5113 """Yield each of the items from *iterable*. If the iteration raises one of
5114 the specified *exceptions*, that exception will be suppressed and iteration
5115 will stop.
5117 >>> from itertools import chain
5118 >>> def breaks_at_five(x):
5119 ... while True:
5120 ... if x >= 5:
5121 ... raise RuntimeError
5122 ... yield x
5123 ... x += 1
5124 >>> it_1 = iter_suppress(breaks_at_five(1), RuntimeError)
5125 >>> it_2 = iter_suppress(breaks_at_five(2), RuntimeError)
5126 >>> list(chain(it_1, it_2))
5127 [1, 2, 3, 4, 2, 3, 4]
5128 """
5129 try:
5130 yield from iterable
5131 except exceptions:
5132 return
5135def filter_map(func, iterable):
5136 """Apply *func* to every element of *iterable*, yielding only those which
5137 are not ``None``.
5139 >>> elems = ['1', 'a', '2', 'b', '3']
5140 >>> list(filter_map(lambda s: int(s) if s.isnumeric() else None, elems))
5141 [1, 2, 3]
5142 """
5143 for x in iterable:
5144 y = func(x)
5145 if y is not None:
5146 yield y
5149def powerset_of_sets(iterable, *, baseset=set):
5150 """Yields all possible subsets of the iterable.
5152 >>> list(powerset_of_sets([1, 2, 3])) # doctest: +SKIP
5153 [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
5154 >>> list(powerset_of_sets([1, 1, 0])) # doctest: +SKIP
5155 [set(), {1}, {0}, {0, 1}]
5157 :func:`powerset_of_sets` takes care to minimize the number
5158 of hash operations performed.
5160 The *baseset* parameter determines what kind of sets are
5161 constructed, either *set* or *frozenset*.
5162 """
5163 sets = tuple(dict.fromkeys(map(frozenset, zip(iterable))))
5164 union = baseset().union
5165 return chain.from_iterable(
5166 starmap(union, combinations(sets, r)) for r in range(len(sets) + 1)
5167 )
5170def join_mappings(**field_to_map):
5171 """
5172 Joins multiple mappings together using their common keys.
5174 >>> user_scores = {'elliot': 50, 'claris': 60}
5175 >>> user_times = {'elliot': 30, 'claris': 40}
5176 >>> join_mappings(score=user_scores, time=user_times)
5177 {'elliot': {'score': 50, 'time': 30}, 'claris': {'score': 60, 'time': 40}}
5178 """
5179 ret = defaultdict(dict)
5181 for field_name, mapping in field_to_map.items():
5182 for key, value in mapping.items():
5183 ret[key][field_name] = value
5185 return dict(ret)
5188def _complex_sumprod(v1, v2):
5189 """High precision sumprod() for complex numbers.
5190 Used by :func:`dft` and :func:`idft`.
5191 """
5193 real = attrgetter('real')
5194 imag = attrgetter('imag')
5195 r1 = chain(map(real, v1), map(neg, map(imag, v1)))
5196 r2 = chain(map(real, v2), map(imag, v2))
5197 i1 = chain(map(real, v1), map(imag, v1))
5198 i2 = chain(map(imag, v2), map(real, v2))
5199 return complex(_fsumprod(r1, r2), _fsumprod(i1, i2))
5202def dft(xarr):
5203 """Discrete Fourier Transform. *xarr* is a sequence of complex numbers.
5204 Yields the components of the corresponding transformed output vector.
5206 >>> import cmath
5207 >>> xarr = [1, 2-1j, -1j, -1+2j] # time domain
5208 >>> Xarr = [2, -2-2j, -2j, 4+4j] # frequency domain
5209 >>> magnitudes, phases = zip(*map(cmath.polar, Xarr))
5210 >>> all(map(cmath.isclose, dft(xarr), Xarr))
5211 True
5213 Inputs are restricted to numeric types that can add and multiply
5214 with a complex number. This includes int, float, complex, and
5215 Fraction, but excludes Decimal.
5217 See :func:`idft` for the inverse Discrete Fourier Transform.
5218 """
5219 N = len(xarr)
5220 roots_of_unity = [e ** (n / N * tau * -1j) for n in range(N)]
5221 for k in range(N):
5222 coeffs = [roots_of_unity[k * n % N] for n in range(N)]
5223 yield _complex_sumprod(xarr, coeffs)
5226def idft(Xarr):
5227 """Inverse Discrete Fourier Transform. *Xarr* is a sequence of
5228 complex numbers. Yields the components of the corresponding
5229 inverse-transformed output vector.
5231 >>> import cmath
5232 >>> xarr = [1, 2-1j, -1j, -1+2j] # time domain
5233 >>> Xarr = [2, -2-2j, -2j, 4+4j] # frequency domain
5234 >>> all(map(cmath.isclose, idft(Xarr), xarr))
5235 True
5237 Inputs are restricted to numeric types that can add and multiply
5238 with a complex number. This includes int, float, complex, and
5239 Fraction, but excludes Decimal.
5241 See :func:`dft` for the Discrete Fourier Transform.
5242 """
5243 N = len(Xarr)
5244 roots_of_unity = [e ** (n / N * tau * 1j) for n in range(N)]
5245 for k in range(N):
5246 coeffs = [roots_of_unity[k * n % N] for n in range(N)]
5247 yield _complex_sumprod(Xarr, coeffs) / N
5250def doublestarmap(func, iterable):
5251 """Apply *func* to every item of *iterable* by dictionary unpacking
5252 the item into *func*.
5254 The difference between :func:`itertools.starmap` and :func:`doublestarmap`
5255 parallels the distinction between ``func(*a)`` and ``func(**a)``.
5257 >>> iterable = [{'a': 1, 'b': 2}, {'a': 40, 'b': 60}]
5258 >>> list(doublestarmap(lambda a, b: a + b, iterable))
5259 [3, 100]
5261 ``TypeError`` will be raised if *func*'s signature doesn't match the
5262 mapping contained in *iterable* or if *iterable* does not contain mappings.
5263 """
5264 for item in iterable:
5265 yield func(**item)
5268def _nth_prime_bounds(n):
5269 """Bounds for the nth prime (counting from 1): lb < p_n < ub."""
5270 # At and above 688,383, the lb/ub spread is under 0.003 * p_n.
5272 if n < 1:
5273 raise ValueError
5275 if n < 6:
5276 return (n, 2.25 * n)
5278 # https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
5279 upper_bound = n * log(n * log(n))
5280 lower_bound = upper_bound - n
5281 if n >= 688_383:
5282 upper_bound -= n * (1.0 - (log(log(n)) - 2.0) / log(n))
5284 return lower_bound, upper_bound
5287def nth_prime(n, *, approximate=False):
5288 """Return the nth prime (counting from 0).
5290 >>> nth_prime(0)
5291 2
5292 >>> nth_prime(100)
5293 547
5295 If *approximate* is set to True, will return a prime close
5296 to the nth prime. The estimation is much faster than computing
5297 an exact result.
5299 >>> nth_prime(200_000_000, approximate=True) # Exact result is 4222234763
5300 4217820427
5302 """
5303 lb, ub = _nth_prime_bounds(n + 1)
5305 if not approximate or n <= 1_000_000:
5306 return nth(sieve(ceil(ub)), n)
5308 # Search from the midpoint and return the first odd prime
5309 odd = floor((lb + ub) / 2) | 1
5310 return first_true(count(odd, step=2), pred=is_prime)
5313def argmin(iterable, *, key=None):
5314 """
5315 Index of the first occurrence of a minimum value in an iterable.
5317 >>> argmin('efghabcdijkl')
5318 4
5319 >>> argmin([3, 2, 1, 0, 4, 2, 1, 0])
5320 3
5322 For example, look up a label corresponding to the position
5323 of a value that minimizes a cost function::
5325 >>> def cost(x):
5326 ... "Days for a wound to heal given a subject's age."
5327 ... return x**2 - 20*x + 150
5328 ...
5329 >>> labels = ['homer', 'marge', 'bart', 'lisa', 'maggie']
5330 >>> ages = [ 35, 30, 10, 9, 1 ]
5332 # Fastest healing family member
5333 >>> labels[argmin(ages, key=cost)]
5334 'bart'
5336 # Age with fastest healing
5337 >>> min(ages, key=cost)
5338 10
5340 """
5341 if key is not None:
5342 iterable = map(key, iterable)
5343 return min(enumerate(iterable), key=itemgetter(1))[0]
5346def argmax(iterable, *, key=None):
5347 """
5348 Index of the first occurrence of a maximum value in an iterable.
5350 >>> argmax('abcdefghabcd')
5351 7
5352 >>> argmax([0, 1, 2, 3, 3, 2, 1, 0])
5353 3
5355 For example, identify the best machine learning model::
5357 >>> models = ['svm', 'random forest', 'knn', 'naïve bayes']
5358 >>> accuracy = [ 68, 61, 84, 72 ]
5360 # Most accurate model
5361 >>> models[argmax(accuracy)]
5362 'knn'
5364 # Best accuracy
5365 >>> max(accuracy)
5366 84
5368 """
5369 if key is not None:
5370 iterable = map(key, iterable)
5371 return max(enumerate(iterable), key=itemgetter(1))[0]
5374def _extract_monotonic(iterator, indices):
5375 'Non-decreasing indices, lazily consumed'
5376 num_read = 0
5377 for index in indices:
5378 advance = index - num_read
5379 try:
5380 value = next(islice(iterator, advance, None))
5381 except ValueError:
5382 if advance != -1 or index < 0:
5383 raise ValueError(f'Invalid index: {index}') from None
5384 except StopIteration:
5385 raise IndexError(index) from None
5386 else:
5387 num_read += advance + 1
5388 yield value
5391def _extract_buffered(iterator, index_and_position):
5392 'Arbitrary index order, greedily consumed'
5393 buffer = {}
5394 iterator_position = -1
5395 next_to_emit = 0
5397 for index, order in index_and_position:
5398 advance = index - iterator_position
5399 if advance:
5400 try:
5401 value = next(islice(iterator, advance - 1, None))
5402 except StopIteration:
5403 raise IndexError(index) from None
5404 iterator_position = index
5406 buffer[order] = value
5408 while next_to_emit in buffer:
5409 yield buffer.pop(next_to_emit)
5410 next_to_emit += 1
5413def extract(iterable, indices, *, monotonic=False):
5414 """Yield values at the specified indices.
5416 Example:
5418 >>> data = 'abcdefghijklmnopqrstuvwxyz'
5419 >>> list(extract(data, [7, 4, 11, 11, 14]))
5420 ['h', 'e', 'l', 'l', 'o']
5422 The *iterable* is consumed lazily and can be infinite.
5424 When *monotonic* is false, the *indices* are consumed immediately
5425 and must be finite. When *monotonic* is true, *indices* are consumed
5426 lazily and can be infinite but must be non-decreasing.
5428 Raises ``IndexError`` if an index lies beyond the iterable.
5429 Raises ``ValueError`` for a negative index or for a decreasing
5430 index when *monotonic* is true.
5431 """
5433 iterator = iter(iterable)
5434 indices = iter(indices)
5436 if monotonic:
5437 return _extract_monotonic(iterator, indices)
5439 index_and_position = sorted(zip(indices, count()))
5440 if index_and_position and index_and_position[0][0] < 0:
5441 raise ValueError('Indices must be non-negative')
5442 return _extract_buffered(iterator, index_and_position)
5445class serialize:
5446 """Wrap a non-concurrent iterator with a lock to enforce sequential access.
5448 Applies a non-reentrant lock around calls to ``__next__``, allowing
5449 iterator and generator instances to be shared by multiple consumer
5450 threads.
5451 """
5453 __slots__ = ('_iterator', '_lock')
5455 def __init__(self, iterable):
5456 self._iterator = iter(iterable)
5457 self._lock = Lock()
5459 def __iter__(self):
5460 return self
5462 def __next__(self):
5463 with self._lock:
5464 return next(self._iterator)
5466 def send(self, value, /):
5467 """Send a value to a generator.
5469 Raises AttributeError if not a generator.
5470 """
5471 with self._lock:
5472 return self._iterator.send(value)
5474 def throw(self, *args):
5475 """Call throw() on a generator.
5477 Raises AttributeError if not a generator.
5478 """
5479 with self._lock:
5480 return self._iterator.throw(*args)
5482 def close(self):
5483 """Call close() on a generator.
5485 Raises AttributeError if not a generator.
5486 """
5487 with self._lock:
5488 return self._iterator.close()
5491def synchronized(func):
5492 """Wrap an iterator-returning callable to make its iterators thread-safe.
5494 Existing itertools and more-itertools can be wrapped so that their
5495 iterator instances are serialized.
5497 For example, ``itertools.count`` does not make thread-safe instances,
5498 but that is easily fixed with::
5500 atomic_counter = synchronized(itertools.count)
5502 Can also be used as a decorator for generator functions definitions
5503 so that the generator instances are serialized::
5505 @synchronized
5506 def enumerate_and_timestamp(iterable):
5507 for count, value in enumerate(iterable):
5508 yield count, time_ns(), value
5510 """
5512 @wraps(func)
5513 def inner(*args, **kwargs):
5514 iterator = func(*args, **kwargs)
5515 return serialize(iterator)
5517 return inner
5520def concurrent_tee(iterable, n=2):
5521 """Variant of itertools.tee() but with guaranteed threading semantics.
5523 Takes a non-threadsafe iterator as an input and creates concurrent
5524 tee objects for other threads to have reliable independent copies of
5525 the data stream.
5527 The new iterators are only thread-safe if consumed within a single thread.
5528 To share just one of the new iterators across multiple threads, wrap it
5529 with :func:`serialize`.
5530 """
5532 if n < 0:
5533 raise ValueError
5534 if n == 0:
5535 return ()
5536 iterator = _concurrent_tee(iterable)
5537 result = [iterator]
5538 for _ in range(n - 1):
5539 result.append(_concurrent_tee(iterator))
5540 return tuple(result)
5543class _concurrent_tee:
5544 __slots__ = ('iterator', 'link', 'lock')
5546 def __init__(self, iterable):
5547 if isinstance(iterable, _concurrent_tee):
5548 self.iterator = iterable.iterator
5549 self.link = iterable.link
5550 self.lock = iterable.lock
5551 else:
5552 self.iterator = iter(iterable)
5553 self.link = [None, None]
5554 self.lock = Lock()
5556 def __iter__(self):
5557 return self
5559 def __next__(self):
5560 link = self.link
5561 if link[1] is None:
5562 with self.lock:
5563 if link[1] is None:
5564 link[0] = next(self.iterator)
5565 link[1] = [None, None]
5566 value, self.link = link
5567 return value
5570def subfactorial(n):
5571 """Number of permutations of *n* elements with no fixed points.
5573 The :func:`subfactorial` function computes the length of
5574 :func:`derangements`. For example, there are 1,854 ways to
5575 rearrange the letters in word "epsilon" without leaving any
5576 letter in its original position:
5578 >>> from more_itertools import derangements, ilen
5579 >>> ilen(derangements('epsilon'))
5580 1854
5581 >>> subfactorial(len('epsilon'))
5582 1854
5584 Reference: https://oeis.org/A000166
5586 """
5587 if n < 0:
5588 raise ValueError
5589 sf = adj = 1
5590 for i in range(n + 1):
5591 sf = sf * i + adj
5592 adj = -adj
5593 return sf
5596def _full_period_lcg(n):
5597 "Returns values from range(n) in randomly shuffled order."
5599 # The algorithm is a fluxed, full period linear congruential generator.
5600 # Size *m* is a power of two. The *mask* speeds-up modulo calculations.
5601 # The multiplier *a* and addend *c* are Hull-Dobell constants. See:
5602 # https://jackgiffin.com/main/pdfs/Random-Number-Generators-T-E-Hull-and-A-R-Dobell.pdf
5603 # The value *x* is a random starting point.
5604 # The *flux* bitfield breaks-up patterns in the LCG.
5606 m = 1 << n.bit_length()
5607 mask = m - 1
5608 a = randrange(5, m, 4) if m > 4 else 1
5609 c = randrange(1, m, 2) if m > 1 else 1
5610 x = randrange(m)
5611 flux = randrange(m)
5613 for _ in repeat(None, m):
5614 index = x ^ flux
5615 if index < n:
5616 yield index
5617 x = (a * x + c) & mask
5620def _random_ordered_indices(n):
5621 "Shuffle batches to mitigate the small state space of the LCG."
5623 # Batched variation of Knuth's Algorithm M in §3.2.2 of TAOCP.
5624 batch_size = 1024
5625 iterable = range(n) if n <= batch_size else _full_period_lcg(n)
5626 for batch in map(list, batched(iterable, batch_size)):
5627 shuffle(batch)
5628 yield from batch
5631def random_ordered_range(*args):
5632 "Return :func:`range` values in randomly shuffled order."
5633 range_object = range(*args)
5634 n = len(range_object)
5635 for index in _random_ordered_indices(n):
5636 yield range_object[index]