more-itertools-3.2.0/0000775000175000017500000000000013117757613013537 5ustar bobo00000000000000more-itertools-3.2.0/more_itertools/0000775000175000017500000000000013117757613016605 5ustar bobo00000000000000more-itertools-3.2.0/more_itertools/__init__.py0000664000175000017500000000010713006760013020675 0ustar bobo00000000000000from more_itertools.more import * from more_itertools.recipes import * more-itertools-3.2.0/more_itertools/more.py0000664000175000017500000013364113117605216020120 0ustar bobo00000000000000from __future__ import print_function from collections import Counter, defaultdict, deque from functools import partial, wraps from heapq import merge from itertools import ( chain, compress, count, dropwhile, groupby, islice, repeat, takewhile, tee ) from operator import itemgetter, lt, gt from sys import maxsize, version_info from six import binary_type, string_types, text_type from six.moves import filter, map, range, zip, zip_longest from .recipes import flatten, take __all__ = [ 'adjacent', 'always_iterable', 'bucket', 'chunked', 'collapse', 'collate', 'consumer', 'count_cycle', 'distinct_permutations', 'distribute', 'divide', 'first', 'groupby_transform', 'ilen', 'interleave_longest', 'interleave', 'intersperse', 'islice_extended', 'iterate', 'locate', 'lstrip', 'numeric_range', 'one', 'padded', 'peekable', 'rstrip', 'side_effect', 'sliced', 'sort_together', 'split_after', 'split_before', 'spy', 'stagger', 'strip', 'unique_to_each', 'windowed', 'with_iter', 'zip_offset', ] _marker = object() def chunked(iterable, n): """Break *iterable* into lists of length *n*: >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) [[1, 2, 3], [4, 5, 6]] If the length of *iterable* is not evenly divisible by *n*, the last returned list will be shorter: >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) [[1, 2, 3], [4, 5, 6], [7, 8]] To use a fill-in value instead, see the :func:`grouper` recipe. :func:`chunked` is useful for splitting up a computation on a large number of keys into batches, to be pickled and sent off to worker processes. One example is operations on rows in MySQL, which does not implement server-side cursors properly and would otherwise load the entire dataset into RAM on the client. """ return iter(partial(take, n, iter(iterable)), []) def first(iterable, default=_marker): """Return the first item of *iterable*, or *default* if *iterable* is empty. >>> first([0, 1, 2, 3]) 0 >>> first([], 'some default') 'some default' If *default* is not provided and there are no items in the iterable, raise ``ValueError``. :func:`first` is useful when you have a generator of expensive-to-retrieve values and want any arbitrary one. It is marginally shorter than ``next(iter(iterable), default)``. """ try: return next(iter(iterable)) except StopIteration: # I'm on the edge about raising ValueError instead of StopIteration. At # the moment, ValueError wins, because the caller could conceivably # want to do something different with flow control when I raise the # exception, and it's weird to explicitly catch StopIteration. if default is _marker: raise ValueError('first() was called on an empty iterable, and no ' 'default value was provided.') return default class peekable(object): """Wrap an iterator to allow lookahead and prepending elements. Call :meth:`peek` on the result to get the value that will be returned by :func:`next`. This won't advance the iterator: >>> p = peekable(['a', 'b']) >>> p.peek() 'a' >>> next(p) 'a' Pass :meth:`peek` a default value to return that instead of raising ``StopIteration`` when the iterator is exhausted. >>> p = peekable([]) >>> p.peek('hi') 'hi' peekables also offer a :meth:`prepend` method, which "inserts" items at the head of the iterable: >>> p = peekable([1, 2, 3]) >>> p.prepend(10, 11, 12) >>> next(p) 10 >>> p.peek() 11 >>> list(p) [11, 12, 1, 2, 3] peekables can be indexed. Index 0 is the item that will be returned by :func:`next`, index 1 is the item after that, and so on: The values up to the given index will be cached. >>> p = peekable(['a', 'b', 'c', 'd']) >>> p[0] 'a' >>> p[1] 'b' >>> next(p) 'a' Negative indexes are supported, but be aware that they will cache the remaining items in the source iterator, which may require significant storage. To check whether a peekable is exhausted, check its truth value: >>> p = peekable(['a', 'b']) >>> if p: # peekable has items ... list(p) ['a', 'b'] >>> if not p: # peekable is exhaused ... list(p) [] """ def __init__(self, iterable): self._it = iter(iterable) self._cache = deque() def __iter__(self): return self def __bool__(self): try: self.peek() except StopIteration: return False return True def __nonzero__(self): # For Python 2 compatibility return self.__bool__() def peek(self, default=_marker): """Return the item that will be next returned from ``next()``. Return ``default`` if there are no items left. If ``default`` is not provided, raise ``StopIteration``. """ if not self._cache: try: self._cache.append(next(self._it)) except StopIteration: if default is _marker: raise return default return self._cache[0] def prepend(self, *items): """Stack up items to be the next ones returned from ``next()`` or ``self.peek()``. The items will be returned in first in, first out order:: >>> p = peekable([1, 2, 3]) >>> p.prepend(10, 11, 12) >>> next(p) 10 >>> list(p) [11, 12, 1, 2, 3] It is possible, by prepending items, to "resurrect" a peekable that previously raised ``StopIteration``. >>> p = peekable([]) >>> next(p) Traceback (most recent call last): ... StopIteration >>> p.prepend(1) >>> next(p) 1 >>> next(p) Traceback (most recent call last): ... StopIteration """ self._cache.extendleft(reversed(items)) def __next__(self): if self._cache: return self._cache.popleft() return next(self._it) def next(self): # For Python 2 compatibility return self.__next__() def _get_slice(self, index): # Normalize the slice's arguments step = 1 if (index.step is None) else index.step if step > 0: start = 0 if (index.start is None) else index.start stop = maxsize if (index.stop is None) else index.stop elif step < 0: start = -1 if (index.start is None) else index.start stop = (-maxsize - 1) if (index.stop is None) else index.stop else: raise ValueError('slice step cannot be zero') # If either the start or stop index is negative, we'll need to cache # the rest of the iterable in order to slice from the right side. if (start < 0) or (stop < 0): self._cache.extend(self._it) # Otherwise we'll need to find the rightmost index and cache to that # point. else: n = min(max(start, stop) + 1, maxsize) cache_len = len(self._cache) if n >= cache_len: self._cache.extend(islice(self._it, n - cache_len)) return list(self._cache)[index] def __getitem__(self, index): if isinstance(index, slice): return self._get_slice(index) cache_len = len(self._cache) if index < 0: self._cache.extend(self._it) elif index >= cache_len: self._cache.extend(islice(self._it, index + 1 - cache_len)) return self._cache[index] def _collate(*iterables, **kwargs): """Helper for ``collate()``, called when the user is using the ``reverse`` or ``key`` keyword arguments on Python versions below 3.5. """ key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = partial(max if reverse else min, key=itemgetter(0)) peekables = [peekable(it) for it in iterables] peekables = [p for p in peekables if p] # Kill empties. while peekables: _, p = min_or_max((key(p.peek()), p) for p in peekables) yield next(p) peekables = [x for x in peekables if x] def collate(*iterables, **kwargs): """Return a sorted merge of the items from each of several already-sorted ``iterables``. >>> list(collate('ACDZ', 'AZ', 'JKL')) ['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z'] Works lazily, keeping only the next value from each iterable in memory. Use :func:`collate` to, for example, perform a n-way mergesort of items that don't fit in memory. :arg key: A function that returns a comparison value for an item. Defaults to the identity function. :arg reverse: If ``reverse=True``, yield results in descending order rather than ascending. ``iterables`` must also yield their elements in descending order. If the elements of the passed-in iterables are out of order, you might get unexpected results. If neither of the keyword arguments are specified, this function delegates to :func:`heapq.merge`. """ if not kwargs: return merge(*iterables) return _collate(*iterables, **kwargs) # If using Python version 3.5 or greater, heapq.merge() will be faster than # collate - use that instead. if version_info >= (3, 5, 0): collate = merge def consumer(func): """Decorator that automatically advances a PEP-342-style "reverse iterator" to its first yield point so you don't have to call ``next()`` on it manually. >>> @consumer ... def tally(): ... i = 0 ... while True: ... print('Thing number %s is %s.' % (i, (yield))) ... i += 1 ... >>> t = tally() >>> t.send('red') Thing number 0 is red. >>> t.send('fish') Thing number 1 is fish. Without the decorator, you would have to call ``next(t)`` before ``t.send()`` could be used. """ @wraps(func) def wrapper(*args, **kwargs): gen = func(*args, **kwargs) next(gen) return gen return wrapper def ilen(iterable): """Return the number of items in *iterable*. >>> ilen(x for x in range(1000000) if x % 3 == 0) 333334 This consumes the iterable, so handle with care. """ d = deque(enumerate(iterable, 1), maxlen=1) return d[0][0] if d else 0 def iterate(func, start): """Return ``start``, ``func(start)``, ``func(func(start))``, ... >>> from itertools import islice >>> list(islice(iterate(lambda x: 2*x, 1), 10)) [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] """ while True: yield start start = func(start) def with_iter(context_manager): """Wrap an iterable in a ``with`` statement, so it closes once exhausted. For example, this will close the file when the iterator is exhausted:: upper_lines = (line.upper() for line in with_iter(open('foo'))) Any context manager which returns an iterable is a candidate for ``with_iter``. """ with context_manager as iterable: for item in iterable: yield item def one(iterable): """Return the only element from the iterable. Raise ValueError if the iterable is empty or longer than 1 element. For example, assert that a DB query returns a single, unique result. >>> one(['val']) 'val' >>> one(['val', 'other']) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: too many values to unpack (expected 1) >>> one([]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: not enough values to unpack (expected 1, got 0) ``one()`` attempts to advance the iterable twice in order to ensure there aren't further items. Because this discards any second item, ``one()`` is not suitable in situations where you want to catch its exception and then try an alternative treatment of the iterable. It should be used only when a iterable longer than 1 item is, in fact, an error. """ element, = iterable return element def distinct_permutations(iterable): """Yield successive distinct permutations of the elements in *iterable*. >>> sorted(distinct_permutations([1, 0, 1])) [(0, 1, 1), (1, 0, 1), (1, 1, 0)] Equivalent to ``set(permutations(iterable))``, except duplicates are not generated and thrown away. For larger input sequences this is much more efficient. Duplicate permutations arise when there are duplicated elements in the input iterable. The number of items returned is `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of items input, and each `x_i` is the count of a distinct item in the input sequence. """ def perm_unique_helper(item_counts, perm, i): """Internal helper function :arg item_counts: Stores the unique items in ``iterable`` and how many times they are repeated :arg perm: The permutation that is being built for output :arg i: The index of the permutation being modified The output permutations are built up recursively; the distinct items are placed until their repetitions are exhausted. """ if i < 0: yield tuple(perm) else: for item in item_counts: if item_counts[item] <= 0: continue perm[i] = item item_counts[item] -= 1 for x in perm_unique_helper(item_counts, perm, i - 1): yield x item_counts[item] += 1 item_counts = {} for item in iterable: item_counts[item] = item_counts.get(item, 0) + 1 return perm_unique_helper(item_counts, [None] * len(iterable), len(iterable) - 1) def intersperse(e, iterable): """Intersperse object *e* between the items of *iterable*. >>> list(intersperse('x', 'ABCD')) ['A', 'x', 'B', 'x', 'C', 'x', 'D'] >>> list(intersperse(None, [1, 2, 3])) [1, None, 2, None, 3] """ it = iter(iterable) filler = repeat(e) zipped = flatten(zip(filler, it)) next(zipped) return zipped def unique_to_each(*iterables): """Return the elements from each of the input iterables that aren't in the other input iterables. For example, suppose you have a set of packages, each with a set of dependencies:: {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} If you remove one package, which dependencies can also be removed? If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) [['A'], ['C'], ['D']] If there are duplicates in one input iterable that aren't in the others they will be duplicated in the output. Input order is preserved:: >>> unique_to_each("mississippi", "missouri") [['p', 'p'], ['o', 'u', 'r']] It is assumed that the elements of each iterable are hashable. """ pool = [list(it) for it in iterables] counts = Counter(chain.from_iterable(map(set, pool))) uniques = {element for element in counts if counts[element] == 1} return [list(filter(uniques.__contains__, it)) for it in pool] def windowed(seq, n, fillvalue=None, step=1): """Return a sliding window of width *n* over the given iterable. >>> all_windows = windowed([1, 2, 3, 4, 5], 3) >>> list(all_windows) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] When the window is larger than the iterable, *fillvalue* is used in place of missing values:: >>> list(windowed([1, 2, 3], 4)) [(1, 2, 3, None)] Each window will advance in increments of *step*: >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2)) [(1, 2, 3), (3, 4, 5), (5, 6, '!')] """ if n < 0: raise ValueError('n must be >= 0') if n == 0: yield tuple() return if step < 1: raise ValueError('step must be >= 1') it = iter(seq) window = deque([], n) append = window.append # Initial deque fill for _ in range(n): append(next(it, fillvalue)) yield tuple(window) # Appending new items to the right causes old items to fall off the left i = 0 for item in it: append(item) i = (i + 1) % step if i % step == 0: yield tuple(window) # If there are items from the iterable in the window, pad with the given # value and emit them. if (i % step) and (step - i < n): for _ in range(step - i): append(fillvalue) yield tuple(window) class bucket(object): """Wrap *iterable* and return an object that buckets it iterable into child iterables based on a *key* function. >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] >>> s = bucket(iterable, key=lambda s: s[0]) >>> a_iterable = s['a'] >>> next(a_iterable) 'a1' >>> next(a_iterable) 'a2' >>> list(s['b']) ['b1', 'b2', 'b3'] The original iterable will be advanced and its items will be cached until they are used by the child iterables. This may require significant storage. Be aware that attempting to select a bucket that no items correspond to will exhaust the iterable and cache all values. """ def __init__(self, iterable, key): self._it = iter(iterable) self._key = key self._cache = defaultdict(deque) def __contains__(self, value): try: item = next(self[value]) except StopIteration: return False else: self._cache[value].appendleft(item) return True def _get_values(self, value): """ Helper to yield items from the parent iterator that match *value*. Items that don't match are stored in the local cache as they are encountered. """ while True: # If we've cached some items that match the target value, emit # the first one and evict it from the cache. if self._cache[value]: yield self._cache[value].popleft() # Otherwise we need to advance the parent iterator to search for # a matching item, caching the rest. else: while True: item = next(self._it) item_value = self._key(item) if item_value == value: yield item break else: self._cache[item_value].append(item) def __getitem__(self, value): return self._get_values(value) def spy(iterable, n=1): """Return a 2-tuple with a list containing the first *n* elements of *iterable*, and an iterator with the same items as *iterable*. This allows you to "look ahead" at the items in the iterable without advancing it. There is one item in the list by default: >>> iterable = 'abcdefg' >>> head, iterable = spy(iterable) >>> head ['a'] >>> list(iterable) ['a', 'b', 'c', 'd', 'e', 'f', 'g'] You may use unpacking to retrieve items instead of lists: >>> (head,), iterable = spy('abcdefg') >>> head 'a' >>> (first, second), iterable = spy('abcdefg', 2) >>> first 'a' >>> second 'b' The number of items requested can be larger than the number of items in the iterable: >>> iterable = [1, 2, 3, 4, 5] >>> head, iterable = spy(iterable, 10) >>> head [1, 2, 3, 4, 5] >>> list(iterable) [1, 2, 3, 4, 5] """ it = iter(iterable) head = take(n, it) return head, chain(head, it) def interleave(*iterables): """Return a new iterable yielding from each iterable in turn, until the shortest is exhausted. >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8])) [1, 4, 6, 2, 5, 7] For a version that doesn't terminate after the shortest iterable is exhausted, see :func:`interleave_longest`. """ return chain.from_iterable(zip(*iterables)) def interleave_longest(*iterables): """Return a new iterable yielding from each iterable in turn, skipping any that are exhausted. >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8])) [1, 4, 6, 2, 5, 7, 3, 8] """ i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker)) return filter(lambda x: x is not _marker, i) def collapse(iterable, base_type=None, levels=None): """Flatten an iterable with multiple levels of nesting (e.g., a list of lists of tuples) into non-iterable types. >>> iterable = [(1, 2), ([3, 4], [[5], [6]])] >>> list(collapse(iterable)) [1, 2, 3, 4, 5, 6] String types are not considered iterable and will not be collapsed. To avoid collapsing other types, specify *base_type*: >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']] >>> list(collapse(iterable, base_type=tuple)) ['ab', ('cd', 'ef'), 'gh', 'ij'] Specify *levels* to stop flattening after a certain level: >>> iterable = [('a', ['b']), ('c', ['d'])] >>> list(collapse(iterable)) # Fully flattened ['a', 'b', 'c', 'd'] >>> list(collapse(iterable, levels=1)) # Only one level flattened ['a', ['b'], 'c', ['d']] """ def walk(node, level): if ( ((levels is not None) and (level > levels)) or isinstance(node, string_types) or ((base_type is not None) and isinstance(node, base_type)) ): yield node return try: tree = iter(node) except TypeError: yield node return else: for child in tree: for x in walk(child, level + 1): yield x for x in walk(iterable, 0): yield x def side_effect(func, iterable, chunk_size=None, before=None, after=None): """Invoke *func* on each item in *iterable* (or on each *chunk_size* group of items) before yielding the item. `func` must be a function that takes a single argument. Its return value will be discarded. *before* and *after* are optional functions that take no arguments. They will be executed before iteration starts and after it ends, respectively. `side_effect` can be used for logging, updating progress bars, or anything that is not functionally "pure." Emitting a status message: >>> from more_itertools import consume >>> func = lambda item: print('Received {}'.format(item)) >>> consume(side_effect(func, range(2))) Received 0 Received 1 Operating on chunks of items: >>> pair_sums = [] >>> func = lambda chunk: pair_sums.append(sum(chunk)) >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2)) [0, 1, 2, 3, 4, 5] >>> list(pair_sums) [1, 5, 9] Writing to a file-like object: >>> from io import StringIO >>> from more_itertools import consume >>> f = StringIO() >>> func = lambda x: print(x, file=f) >>> before = lambda: print(u'HEADER', file=f) >>> after = f.close >>> it = [u'a', u'b', u'c'] >>> consume(side_effect(func, it, before=before, after=after)) >>> f.closed True """ try: if before is not None: before() if chunk_size is None: for item in iterable: func(item) yield item else: for chunk in chunked(iterable, chunk_size): func(chunk) for item in chunk: yield item finally: if after is not None: after() def sliced(seq, n): """Yield slices of length *n* from the sequence *seq*. >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) [(1, 2, 3), (4, 5, 6)] If the length of the sequence is not divisible by the requested slice length, the last slice will be shorter. >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3)) [(1, 2, 3), (4, 5, 6), (7, 8)] This function will only work for iterables that support slicing. For non-sliceable iterables, see :func:`chunked`. """ return takewhile(bool, (seq[i: i + n] for i in count(0, n))) def split_before(iterable, pred): """Yield lists of items from *iterable*, where each list starts with an item where callable *pred* returns ``True``: >>> list(split_before('OneTwo', lambda s: s.isupper())) [['O', 'n', 'e'], ['T', 'w', 'o']] >>> list(split_before(range(10), lambda n: n % 3 == 0)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] """ buf = [] for item in iterable: if pred(item) and buf: yield buf buf = [] buf.append(item) yield buf def split_after(iterable, pred): """Yield lists of items from *iterable*, where each list ends with an item where callable *pred* returns ``True``: >>> list(split_after('one1two2', lambda s: s.isdigit())) [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']] >>> list(split_after(range(10), lambda n: n % 3 == 0)) [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]] """ buf = [] for item in iterable: buf.append(item) if pred(item) and buf: yield buf buf = [] if buf: yield buf def padded(iterable, fillvalue=None, n=None, next_multiple=False): """Yield the elements from *iterable*, followed by *fillvalue*, such that at least *n* items are emitted. >>> list(padded([1, 2, 3], '?', 5)) [1, 2, 3, '?', '?'] If *next_multiple* is ``True``, *fillvalue* will be emitted until the number of items emitted is a multiple of *n*:: >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True)) [1, 2, 3, 4, None, None] If *n* is ``None``, *fillvalue* will be emitted indefinitely. """ it = iter(iterable) if n is None: for item in chain(it, repeat(fillvalue)): yield item elif n < 1: raise ValueError('n must be at least 1') else: item_count = 0 for item in it: yield item item_count += 1 remaining = (n - item_count) % n if next_multiple else n - item_count for _ in range(remaining): yield fillvalue def distribute(n, iterable): """Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned iterables will not be identical: >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7]) >>> [list(c) for c in children] [[1, 4, 7], [2, 5], [3, 6]] If the length of *iterable* is smaller than *n*, then the last returned iterables will be empty: >>> children = distribute(5, [1, 2, 3]) >>> [list(c) for c in children] [[1], [2], [3], [], []] This function uses :func:`itertools.tee` and may require significant storage. If you need the order items in the smaller iterables to match the original iterable, see :func:`divide`. """ if n < 1: raise ValueError('n must be at least 1') children = tee(iterable, n) return [islice(it, index, None, n) for index, it in enumerate(children)] def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None): """Yield tuples whose elements are offset from *iterable*. The amount by which the `i`-th item in each tuple is offset is given by the `i`-th item in *offsets*. >>> list(stagger([0, 1, 2, 3])) [(None, 0, 1), (0, 1, 2), (1, 2, 3)] >>> list(stagger(range(8), offsets=(0, 2, 4))) [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] By default, the sequence will end when the final element of a tuple is the last item in the iterable. To continue until the first element of a tuple is the last item in the iterable, set *longest* to ``True``:: >>> list(stagger([0, 1, 2, 3], longest=True)) [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] By default, ``None`` will be used to replace offsets beyond the end of the sequence. Specify *fillvalue* to use some other value. """ children = tee(iterable, len(offsets)) return zip_offset( *children, offsets=offsets, longest=longest, fillvalue=fillvalue ) def zip_offset(*iterables, **kwargs): """``zip`` the input *iterables* together, but offset the `i`-th iterable by the `i`-th item in *offsets*. >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1))) [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')] This can be used as a lightweight alternative to SciPy or pandas to analyze data sets in which somes series have a lead or lag relationship. By default, the sequence will end when the shortest iterable is exhausted. To continue until the longest iterable is exhausted, set *longest* to ``True``. >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True)) [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')] By default, ``None`` will be used to replace offsets beyond the end of the sequence. Specify *fillvalue* to use some other value. """ offsets = kwargs['offsets'] longest = kwargs.get('longest', False) fillvalue = kwargs.get('fillvalue', None) if len(iterables) != len(offsets): raise ValueError("Number of iterables and offsets didn't match") staggered = [] for it, n in zip(iterables, offsets): if n < 0: staggered.append(chain(repeat(fillvalue, -n), it)) elif n > 0: staggered.append(islice(it, n, None)) else: staggered.append(it) if longest: return zip_longest(*staggered, fillvalue=fillvalue) return zip(*staggered) def sort_together(iterables, key_list=(0,), reverse=False): """Return the input iterables sorted together, with *key_list* as the priority for sorting. All iterables are trimmed to the length of the shortest one. This can be used like the sorting function in a spreadsheet. If each iterable represents a column of data, the key list determines which columns are used for sorting. By default, all iterables are sorted using the ``0``-th iterable:: >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')] >>> sort_together(iterables) [(1, 2, 3, 4), ('d', 'c', 'b', 'a')] Set a different key list to sort according to another iterable. Specifying mutliple keys dictates how ties are broken:: >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')] >>> sort_together(iterables, key_list=(1, 2)) [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')] Set *reverse* to ``True`` to sort in descending order. >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True) [(3, 2, 1), ('a', 'b', 'c')] """ return list(zip(*sorted(zip(*iterables), key=itemgetter(*key_list), reverse=reverse))) def divide(n, iterable): """Divide the elements from *iterable* into *n* parts, maintaining order. >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 2, 3] >>> list(group_2) [4, 5, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned iterables will not be identical: >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) >>> [list(c) for c in children] [[1, 2, 3], [4, 5], [6, 7]] If the length of the iterable is smaller than n, then the last returned iterables will be empty: >>> children = divide(5, [1, 2, 3]) >>> [list(c) for c in children] [[1], [2], [3], [], []] This function will exhaust the iterable before returning and may require significant storage. If order is not important, see :func:`distribute`, which does not first pull the iterable into memory. """ if n < 1: raise ValueError('n must be at least 1') seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) return ret def always_iterable(obj): """ Given an object, always return an iterable. If the object is not already iterable, return a tuple containing containing the object:: >>> always_iterable(1) (1,) If the object is ``None``, return an empty iterable:: >>> always_iterable(None) () Otherwise, return the object itself:: >>> always_iterable([1, 2, 3]) [1, 2, 3] Strings (binary or unicode) are not considered to be iterable:: >>> always_iterable('foo') ('foo',) This function is useful in applications where a passed parameter may be either a single item or a collection of items:: >>> def item_sum(param): ... total = 0 ... for item in always_iterable(param): ... total += item ... ... return total >>> item_sum(10) 10 >>> item_sum([10, 20]) 30 """ if obj is None: return () string_like_types = (text_type, binary_type) if isinstance(obj, string_like_types) or not hasattr(obj, '__iter__'): return obj, return obj def adjacent(predicate, iterable, distance=1): """Return an iterable over `(bool, item)` tuples where the `item` is drawn from *iterable* and the `bool` indicates whether that item satisfies the *predicate* or is adjacent to an item that does. For example, to find whether items are adjacent to a ``3``:: >>> list(adjacent(lambda x: x == 3, range(6))) [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)] Set *distance* to change what counts as adjacent. For example, to find whether items are two places away from a ``3``: >>> list(adjacent(lambda x: x == 3, range(6), distance=2)) [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)] This is useful for contextualizing the results of a search function. For example, a code comparison tool might want to identify lines that have changed, but also surrounding lines to give the viewer of the diff context. The predicate function will only be called once for each item in the iterable. See also :func:`groupby_transform`, which can be used with this function to group ranges of items with the same `bool` value. """ # Allow distance=0 mainly for testing that it reproduces results with map() if distance < 0: raise ValueError('distance must be at least 0') i1, i2 = tee(iterable) padding = [False] * distance selected = chain(padding, map(predicate, i1), padding) adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1)) return zip(adjacent_to_selected, i2) def groupby_transform(iterable, keyfunc=None, valuefunc=None): """An extension of :func:`itertools.groupby` that transforms the values of *iterable* after grouping them. *keyfunc* is a function used to compute a grouping key for each item. *valuefunc* is a function for transforming the items after grouping. >>> iterable = 'AaaABbBCcA' >>> keyfunc = lambda x: x.upper() >>> valuefunc = lambda x: x.lower() >>> grouper = groupby_transform(iterable, keyfunc, valuefunc) >>> [(k, ''.join(g)) for k, g in grouper] [('A', 'aaaa'), ('B', 'bbb'), ('C', 'cc'), ('A', 'a')] *keyfunc* and *valuefunc* default to identity functions if they are not specified. :func:`groupby_transform` is useful when grouping elements of an iterable using a separate iterable as the key. To do this, :func:`zip` the iterables and pass a *keyfunc* that extracts the first element and a *valuefunc* that extracts the second element:: >>> from operator import itemgetter >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3] >>> values = 'abcdefghi' >>> iterable = zip(keys, values) >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1)) >>> [(k, ''.join(g)) for k, g in grouper] [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')] """ valuefunc = (lambda x: x) if valuefunc is None else valuefunc return ((k, map(valuefunc, g)) for k, g in groupby(iterable, keyfunc)) def numeric_range(*args): """An extension of the built-in ``range()`` function whose arguments can be any orderable numeric type. With only *stop* specified, *start* defaults to ``0`` and *step* defaults to ``1``. The output items will match the type of *stop*: >>> list(numeric_range(3.5)) [0.0, 1.0, 2.0, 3.0] With only *start* and *stop* specified, *step* defaults to ``1``. The output items will match the type of *start*: >>> from decimal import Decimal >>> start = Decimal('2.1') >>> stop = Decimal('5.1') >>> list(numeric_range(start, stop)) [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')] With *start*, *stop*, and *step* specified the output items will match the type of ``start + step``: >>> from fractions import Fraction >>> start = Fraction(1, 2) # Start at 1/2 >>> stop = Fraction(5, 2) # End at 5/2 >>> step = Fraction(1, 2) # Count by 1/2 >>> list(numeric_range(start, stop, step)) [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)] If *step* is zero, ``ValueError`` is raised. Negative steps are supported: >>> list(numeric_range(3, -1, -1.0)) [3.0, 2.0, 1.0, 0.0] Be aware of the limitations of floating point numbers; the representation of the yielded numbers may be surprising. """ argc = len(args) if argc == 1: stop, = args start = type(stop)(0) step = 1 elif argc == 2: start, stop = args step = 1 elif argc == 3: start, stop, step = args else: err_msg = 'numeric_range takes at most 3 arguments, got {}' raise TypeError(err_msg.format(argc)) values = (start + (step * n) for n in count()) if step > 0: return takewhile(partial(gt, stop), values) elif step < 0: return takewhile(partial(lt, stop), values) else: raise ValueError('numeric_range arg 3 must not be zero') def count_cycle(iterable, n=None): """Cycle through the items from *iterable* up to *n* times, yielding the number of completed cycles along with each item. If *n* is omitted the process repeats indefinitely. >>> list(count_cycle('AB', 3)) [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] """ iterable = tuple(iterable) if not iterable: return iter(()) counter = count() if n is None else range(n) return ((i, item) for i in counter for item in iterable) def locate(iterable, pred=bool): """Yield the index of each item in *iterable* for which *pred* returns ``True``. *pred* defaults to :func:`bool`, which will select truthy items: >>> list(locate([0, 1, 1, 0, 1, 0, 0])) [1, 2, 4] Set *pred* to a custom function to, e.g., find the indexes for a particular item: >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b')) [1, 3] Use with :func:`windowed` to find the indexes of a sub-sequence: >>> from more_itertools import windowed >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] >>> sub = [1, 2, 3] >>> pred = lambda w: w == tuple(sub) # windowed() returns tuples >>> list(locate(windowed(iterable, len(sub)), pred=pred)) [1, 5, 9] """ return compress(count(), map(pred, iterable)) def lstrip(iterable, pred): """Yield the items from *iterable*, but strip any from the beginning for which *pred* returns ``True``. For example, to remove a set of items from the start of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(lstrip(iterable, pred)) [1, 2, None, 3, False, None] This function is analagous to to :func:`str.lstrip`. """ return dropwhile(pred, iterable) def rstrip(iterable, pred): """Yield the items from *iterable*, but strip any from the end for which *pred* returns ``True``. For example, to remove a set of items from the end of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(rstrip(iterable, pred)) [None, False, None, 1, 2, None, 3] This function is analagous to :func:`str.rstrip`. """ cache = [] cache_append = cache.append for x in iterable: if pred(x): cache_append(x) else: for y in cache: yield y del cache[:] yield x def strip(iterable, pred): """Yield the items from *iterable*, but strip any from the beginning and end for which *pred* returns ``True``. For example, to remove a set of items from both ends of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(strip(iterable, pred)) [1, 2, None, 3] This function is analagous to :func:`str.strip`. """ return rstrip(lstrip(iterable, pred), pred) def islice_extended(iterable, *args): """An extension of :func:`itertools.islice` that supports negative values for *stop*, *start*, and *step*. >>> iterable = iter('abcdefgh') >>> list(islice_extended(iterable, -4, -1)) ['e', 'f', 'g'] Slices with negative values require some caching of *iterable*, but this function takes care to minimize the amount of memory required. For example, you can use a negative step with an infinite iterator: >>> from itertools import count >>> list(islice_extended(count(), 110, 99, -2)) [110, 108, 106, 104, 102, 100] """ s = slice(*args) start = s.start stop = s.stop if s.step == 0: raise ValueError('step argument must be a non-zero integer or None.') step = s.step or 1 it = iter(iterable) if step > 0: start = 0 if (start is None) else start if (start < 0): # Consume all but the last -start items cache = deque(enumerate(it, 1), maxlen=-start) len_iter = cache[-1][0] if cache else 0 # Adjust start to be positive i = max(len_iter + start, 0) # Adjust stop to be positive if stop is None: j = len_iter elif stop >= 0: j = min(stop, len_iter) else: j = max(len_iter + stop, 0) # Slice the cache n = j - i if n <= 0: return for index, item in islice(cache, None, n, step): yield item elif (stop is not None) and (stop < 0): # Advance to the start position next(islice(it, start, start), None) # When stop is negative, we have to carry -stop items while # iterating cache = deque(islice(it, -stop), maxlen=-stop) for index, item in enumerate(it): cached_item = cache.popleft() if index % step == 0: yield cached_item cache.append(item) else: # When both start and stop are positive we have the normal case for item in islice(it, start, stop, step): yield item else: start = -1 if (start is None) else start if (stop is not None) and (stop < 0): # Consume all but the last items n = -stop - 1 cache = deque(enumerate(it, 1), maxlen=n) len_iter = cache[-1][0] if cache else 0 # If start and stop are both negative they are comparable and # we can just slice. Otherwise we can adjust start to be negative # and then slice. if start < 0: i, j = start, stop else: i, j = min(start - len_iter, -1), None for index, item in list(cache)[i:j:step]: yield item else: # Advance to the stop position if stop is not None: m = stop + 1 next(islice(it, m, m), None) # stop is positive, so if start is negative they are not comparable # and we need the rest of the items. if start < 0: i = start n = None # stop is None and start is positive, so we just need items up to # the start index. elif stop is None: i = None n = start + 1 # Both stop and start are positive, so they are comparable. else: i = None n = start - stop if n <= 0: return cache = list(islice(it, n)) for item in cache[i::step]: yield item more-itertools-3.2.0/more_itertools/recipes.py0000664000175000017500000003246313117605216020610 0ustar bobo00000000000000"""Imported from the recipes section of the itertools documentation. All functions taken from the recipes section of the itertools library docs [1]_. Some backward-compatible usability improvements have been made. .. [1] http://docs.python.org/library/itertools.html#recipes """ from collections import deque from itertools import ( chain, combinations, count, cycle, groupby, islice, repeat, starmap, tee ) import operator from random import randrange, sample, choice from six import PY2 from six.moves import filter, filterfalse, map, range, zip, zip_longest __all__ = [ 'accumulate', 'all_equal', 'consume', 'dotproduct', 'first_true', 'flatten', 'grouper', 'iter_except', 'ncycles', 'nth', 'padnone', 'pairwise', 'partition', 'powerset', 'quantify', 'random_combination_with_replacement', 'random_combination', 'random_permutation', 'random_product', 'repeatfunc', 'roundrobin', 'tabulate', 'tail', 'take', 'unique_everseen', 'unique_justseen', ] def accumulate(iterable, func=operator.add): """ Return an iterator whose items are the accumulated results of a function (specified by the optional *func* argument) that takes two arguments. By default, returns accumulated sums with :func:`operator.add`. >>> list(accumulate([1, 2, 3, 4, 5])) # Running sum [1, 3, 6, 10, 15] >>> list(accumulate([1, 2, 3], func=operator.mul)) # Running product [1, 2, 6] >>> list(accumulate([0, 1, -1, 2, 3, 2], func=max)) # Running maximum [0, 1, 1, 2, 3, 3] This function is available in the ``itertools`` module for Python 3.2 and greater. """ it = iter(iterable) try: total = next(it) except StopIteration: return else: yield total for element in it: total = func(total, element) yield total def take(n, iterable): """Return first *n* items of the iterable as a list. >>> take(3, range(10)) [0, 1, 2] >>> take(5, range(3)) [0, 1, 2] Effectively a short replacement for ``next`` based iterator consumption when you want more than one item, but less than the whole iterator. """ return list(islice(iterable, n)) def tabulate(function, start=0): """Return an iterator over the results of ``func(start)``, ``func(start + 1)``, ``func(start + 2)``... *func* should be a function that accepts one integer argument. If *start* is not specified it defaults to 0. It will be incremented each time the iterator is advanced. >>> square = lambda x: x ** 2 >>> iterator = tabulate(square, -3) >>> take(4, iterator) [9, 4, 1, 0] """ return map(function, count(start)) def tail(n, iterable): """Return an iterator over the last *n* items of *iterable*. >>> t = tail(3, 'ABCDEFG') >>> list(t) ['E', 'F', 'G'] """ return iter(deque(iterable, maxlen=n)) def consume(iterator, n=None): """Advance *iterable* by *n* steps. If *n* is ``None``, consume it entirely. Efficiently exhausts an iterator without returning values. Defaults to consuming the whole iterator, but an optional second argument may be provided to limit consumption. >>> i = (x for x in range(10)) >>> next(i) 0 >>> consume(i, 3) >>> next(i) 4 >>> consume(i) >>> next(i) Traceback (most recent call last): File "", line 1, in StopIteration If the iterator has fewer items remaining than the provided limit, the whole iterator will be consumed. >>> i = (x for x in range(3)) >>> consume(i, 5) >>> next(i) Traceback (most recent call last): File "", line 1, in StopIteration """ # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) def nth(iterable, n, default=None): """Returns the nth item or a default value. >>> l = range(10) >>> nth(l, 3) 3 >>> nth(l, 20, "zebra") 'zebra' """ return next(islice(iterable, n, None), default) def all_equal(iterable): """ Returns ``True`` if all the elements are equal to each other. >>> all_equal('aaaa') True >>> all_equal('aaab') False """ g = groupby(iterable) return next(g, True) and not next(g, False) def quantify(iterable, pred=bool): """Return the how many times the predicate is true. >>> quantify([True, False, True]) 2 """ return sum(map(pred, iterable)) def padnone(iterable): """Returns the sequence of elements and then returns ``None`` indefinitely. >>> take(5, padnone(range(3))) [0, 1, 2, None, None] Useful for emulating the behavior of the built-in :func:`map` function. See also :func:`padded`. """ return chain(iterable, repeat(None)) def ncycles(iterable, n): """Returns the sequence elements *n* times >>> list(ncycles(["a", "b"], 3)) ['a', 'b', 'a', 'b', 'a', 'b'] """ return chain.from_iterable(repeat(tuple(iterable), n)) def dotproduct(vec1, vec2): """Returns the dot product of the two iterables. >>> dotproduct([10, 10], [20, 20]) 400 """ return sum(map(operator.mul, vec1, vec2)) def flatten(listOfLists): """Return an iterator flattening one level of nesting in a list of lists. >>> list(flatten([[0, 1], [2, 3]])) [0, 1, 2, 3] See also :func:`collapse`, which can flatten multiple levels of nesting. """ return chain.from_iterable(listOfLists) def repeatfunc(func, times=None, *args): """Call *func* with *args* repeatedly, returning an iterable over the results. If *times* is specified, the iterable will terminate after that many repetitions: >>> from operator import add >>> times = 4 >>> args = 3, 5 >>> list(repeatfunc(add, times, *args)) [8, 8, 8, 8] If *times* is ``None`` the iterable will not terminate: >>> from random import randrange >>> times = None >>> args = 1, 11 >>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP [2, 4, 8, 1, 8, 4] """ if times is None: return starmap(func, repeat(args)) return starmap(func, repeat(args, times)) def pairwise(iterable): """Returns an iterator of paired items, overlapping, from the original >>> take(4, pairwise(count())) [(0, 1), (1, 2), (2, 3), (3, 4)] """ a, b = tee(iterable) next(b, None) return zip(a, b) def grouper(n, iterable, fillvalue=None): """Collect data into fixed-length chunks or blocks. >>> list(grouper(3, 'ABCDEFG', 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] """ args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) def roundrobin(*iterables): """Yields an item from each iterable, alternating between them. >>> list(roundrobin('ABC', 'D', 'EF')) ['A', 'D', 'E', 'B', 'F', 'C'] See :func:`interleave_longest` for a slightly faster implementation. """ # Recipe credited to George Sakkis pending = len(iterables) if PY2: nexts = cycle(iter(it).next for it in iterables) else: nexts = cycle(iter(it).__next__ for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) def partition(pred, iterable): """ Returns a 2-tuple of iterables derived from the input iterable. The first yields the items that have ``pred(item) == False``. The second yields the items that have ``pred(item) == True``. >>> is_odd = lambda x: x % 2 != 0 >>> iterable = range(10) >>> even_items, odd_items = partition(is_odd, iterable) >>> list(even_items), list(odd_items) ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) """ # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) def powerset(iterable): """Yields all possible subsets of the iterable. >>> list(powerset([1,2,3])) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] """ s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) def unique_everseen(iterable, key=None): """ Yield unique elements, preserving order. >>> list(unique_everseen('AAAABBBCCDAABBB')) ['A', 'B', 'C', 'D'] >>> list(unique_everseen('ABBCcAD', str.lower)) ['A', 'B', 'C', 'D'] Sequences with a mix of hashable and unhashable items can be used. The function will be slower (i.e., `O(n^2)`) for unhashable items. """ seenset = set() seenset_add = seenset.add seenlist = [] seenlist_add = seenlist.append if key is None: for element in iterable: try: if element not in seenset: seenset_add(element) yield element except TypeError as e: if element not in seenlist: seenlist_add(element) yield element else: for element in iterable: k = key(element) try: if k not in seenset: seenset_add(k) yield element except TypeError as e: if k not in seenlist: seenlist_add(k) yield element def unique_justseen(iterable, key=None): """Yields elements in order, ignoring serial duplicates >>> list(unique_justseen('AAAABBBCCDAABBB')) ['A', 'B', 'C', 'D', 'A', 'B'] >>> list(unique_justseen('ABBCcAD', str.lower)) ['A', 'B', 'C', 'A', 'D'] """ return map(next, map(operator.itemgetter(1), groupby(iterable, key))) def iter_except(func, exception, first=None): """Yields results from a function repeatedly until an exception is raised. Converts a call-until-exception interface to an iterator interface. Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel to end the loop. >>> l = [0, 1, 2] >>> list(iter_except(l.pop, IndexError)) [2, 1, 0] """ try: if first is not None: yield first() while 1: yield func() except exception: pass def first_true(iterable, default=False, pred=None): """ Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which ``pred(item) == True`` . >>> first_true(range(10)) 1 >>> first_true(range(10), pred=lambda x: x > 5) 6 >>> first_true(range(10), default='missing', pred=lambda x: x > 9) 'missing' """ return next(filter(pred, iterable), default) def random_product(*args, **kwds): """Draw an item at random from each of the input iterables. >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP ('c', 3, 'Z') If *repeat* is provided as a keyword argument, that many items will be drawn from each iterable. >>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP ('a', 2, 'd', 3) This equivalent to taking a random selection from ``itertools.product(*args, **kwarg)``. """ pools = [tuple(pool) for pool in args] * kwds.get('repeat', 1) return tuple(choice(pool) for pool in pools) def random_permutation(iterable, r=None): """Return a random *r* length permutation of the elements in *iterable*. If *r* is not specified or is ``None``, then *r* defaults to the length of *iterable*. >>> random_permutation(range(5)) # doctest:+SKIP (3, 4, 0, 1, 2) This equivalent to taking a random selection from ``itertools.permutations(iterable, r)``. """ pool = tuple(iterable) r = len(pool) if r is None else r return tuple(sample(pool, r)) def random_combination(iterable, r): """Return a random *r* length subsequence of the elements in *iterable*. >>> random_combination(range(5), 3) # doctest:+SKIP (2, 3, 4) This equivalent to taking a random selection from ``itertools.combinations(iterable, r)``. """ pool = tuple(iterable) n = len(pool) indices = sorted(sample(range(n), r)) return tuple(pool[i] for i in indices) def random_combination_with_replacement(iterable, r): """Return a random *r* length subsequence of elements in *iterable*, allowing individual elements to be repeated. >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP (0, 0, 1, 2, 2) This equivalent to taking a random selection from ``itertools.combinations_with_replacement(iterable, r)``. """ pool = tuple(iterable) n = len(pool) indices = sorted(randrange(n) for i in range(r)) return tuple(pool[i] for i in indices) more-itertools-3.2.0/more_itertools/tests/0000775000175000017500000000000013117757613017747 5ustar bobo00000000000000more-itertools-3.2.0/more_itertools/tests/__init__.py0000664000175000017500000000000013006760013022027 0ustar bobo00000000000000more-itertools-3.2.0/more_itertools/tests/test_recipes.py0000664000175000017500000004122313023131562022775 0ustar bobo00000000000000from random import seed from unittest import TestCase from nose.tools import eq_, assert_raises, ok_ from six.moves import range from more_itertools import * def setup_module(): seed(1337) class AccumulateTests(TestCase): """Tests for ``accumulate()``""" def test_empty(self): """Test that an empty input returns an empty output""" eq_(list(accumulate([])), []) def test_default(self): """Test accumulate with the default function (addition)""" eq_(list(accumulate([1, 2, 3])), [1, 3, 6]) def test_bogus_function(self): """Test accumulate with an invalid function""" with self.assertRaises(TypeError): list(accumulate([1, 2, 3], func=lambda x: x)) def test_custom_function(self): """Test accumulate with a custom function""" eq_(list(accumulate((1, 2, 3, 2, 1), func=max)), [1, 2, 3, 3, 3]) class TakeTests(TestCase): """Tests for ``take()``""" def test_simple_take(self): """Test basic usage""" t = take(5, range(10)) eq_(t, [0, 1, 2, 3, 4]) def test_null_take(self): """Check the null case""" t = take(0, range(10)) eq_(t, []) def test_negative_take(self): """Make sure taking negative items results in a ValueError""" assert_raises(ValueError, take, -3, range(10)) def test_take_too_much(self): """Taking more than an iterator has remaining should return what the iterator has remaining. """ t = take(10, range(5)) eq_(t, [0, 1, 2, 3, 4]) class TabulateTests(TestCase): """Tests for ``tabulate()``""" def test_simple_tabulate(self): """Test the happy path""" t = tabulate(lambda x: x) f = tuple([next(t) for _ in range(3)]) eq_(f, (0, 1, 2)) def test_count(self): """Ensure tabulate accepts specific count""" t = tabulate(lambda x: 2 * x, -1) f = (next(t), next(t), next(t)) eq_(f, (-2, 0, 2)) class TailTests(TestCase): """Tests for ``tail()``""" def test_greater(self): """Length of iterable is greather than requested tail""" eq_(list(tail(3, 'ABCDEFG')), ['E', 'F', 'G']) def test_equal(self): """Length of iterable is equal to the requested tail""" eq_(list(tail(7, 'ABCDEFG')), ['A', 'B', 'C', 'D', 'E', 'F', 'G']) def test_less(self): """Length of iterable is less than requested tail""" eq_(list(tail(8, 'ABCDEFG')), ['A', 'B', 'C', 'D', 'E', 'F', 'G']) class ConsumeTests(TestCase): """Tests for ``consume()``""" def test_sanity(self): """Test basic functionality""" r = (x for x in range(10)) consume(r, 3) eq_(3, next(r)) def test_null_consume(self): """Check the null case""" r = (x for x in range(10)) consume(r, 0) eq_(0, next(r)) def test_negative_consume(self): """Check that negative consumsion throws an error""" r = (x for x in range(10)) assert_raises(ValueError, consume, r, -1) def test_total_consume(self): """Check that iterator is totally consumed by default""" r = (x for x in range(10)) consume(r) assert_raises(StopIteration, next, r) class NthTests(TestCase): """Tests for ``nth()``""" def test_basic(self): """Make sure the nth item is returned""" l = range(10) for i, v in enumerate(l): eq_(nth(l, i), v) def test_default(self): """Ensure a default value is returned when nth item not found""" l = range(3) eq_(nth(l, 100, "zebra"), "zebra") def test_negative_item_raises(self): """Ensure asking for a negative item raises an exception""" assert_raises(ValueError, nth, range(10), -3) class AllEqualTests(TestCase): """Tests for ``all_equal()``""" def test_true(self): """Everything is equal""" self.assertTrue(all_equal('aaaaaa')) self.assertTrue(all_equal([0, 0, 0, 0])) def test_false(self): """Not everything is equal""" self.assertFalse(all_equal('aaaaab')) self.assertFalse(all_equal([0, 0, 0, 1])) def test_tricky(self): """Not everything is identical, but everything is equal""" items = [1, complex(1, 0), 1.0] self.assertTrue(all_equal(items)) def test_empty(self): """Return True if the iterable is empty""" self.assertTrue(all_equal('')) self.assertTrue(all_equal([])) def test_one(self): """Return True if the iterable is singular""" self.assertTrue(all_equal('0')) self.assertTrue(all_equal([0])) class QuantifyTests(TestCase): """Tests for ``quantify()``""" def test_happy_path(self): """Make sure True count is returned""" q = [True, False, True] eq_(quantify(q), 2) def test_custom_predicate(self): """Ensure non-default predicates return as expected""" q = range(10) eq_(quantify(q, lambda x: x % 2 == 0), 5) class PadnoneTests(TestCase): """Tests for ``padnone()``""" def test_happy_path(self): """wrapper iterator should return None indefinitely""" r = range(2) p = padnone(r) eq_([0, 1, None, None], [next(p) for _ in range(4)]) class NcyclesTests(TestCase): """Tests for ``nyclces()``""" def test_happy_path(self): """cycle a sequence three times""" r = ["a", "b", "c"] n = ncycles(r, 3) eq_(["a", "b", "c", "a", "b", "c", "a", "b", "c"], list(n)) def test_null_case(self): """asking for 0 cycles should return an empty iterator""" n = ncycles(range(100), 0) assert_raises(StopIteration, next, n) def test_pathalogical_case(self): """asking for negative cycles should return an empty iterator""" n = ncycles(range(100), -10) assert_raises(StopIteration, next, n) class DotproductTests(TestCase): """Tests for ``dotproduct()``'""" def test_happy_path(self): """simple dotproduct example""" eq_(400, dotproduct([10, 10], [20, 20])) class FlattenTests(TestCase): """Tests for ``flatten()``""" def test_basic_usage(self): """ensure list of lists is flattened one level""" f = [[0, 1, 2], [3, 4, 5]] eq_(list(range(6)), list(flatten(f))) def test_single_level(self): """ensure list of lists is flattened only one level""" f = [[0, [1, 2]], [[3, 4], 5]] eq_([0, [1, 2], [3, 4], 5], list(flatten(f))) class RepeatfuncTests(TestCase): """Tests for ``repeatfunc()``""" def test_simple_repeat(self): """test simple repeated functions""" r = repeatfunc(lambda: 5) eq_([5, 5, 5, 5, 5], [next(r) for _ in range(5)]) def test_finite_repeat(self): """ensure limited repeat when times is provided""" r = repeatfunc(lambda: 5, times=5) eq_([5, 5, 5, 5, 5], list(r)) def test_added_arguments(self): """ensure arguments are applied to the function""" r = repeatfunc(lambda x: x, 2, 3) eq_([3, 3], list(r)) def test_null_times(self): """repeat 0 should return an empty iterator""" r = repeatfunc(range, 0, 3) assert_raises(StopIteration, next, r) class PairwiseTests(TestCase): """Tests for ``pairwise()``""" def test_base_case(self): """ensure an iterable will return pairwise""" p = pairwise([1, 2, 3]) eq_([(1, 2), (2, 3)], list(p)) def test_short_case(self): """ensure an empty iterator if there's not enough values to pair""" p = pairwise("a") assert_raises(StopIteration, next, p) class GrouperTests(TestCase): """Tests for ``grouper()``""" def test_even(self): """Test when group size divides evenly into the length of the iterable. """ eq_(list(grouper(3, 'ABCDEF')), [('A', 'B', 'C'), ('D', 'E', 'F')]) def test_odd(self): """Test when group size does not divide evenly into the length of the iterable. """ eq_(list(grouper(3, 'ABCDE')), [('A', 'B', 'C'), ('D', 'E', None)]) def test_fill_value(self): """Test that the fill value is used to pad the final group""" eq_(list(grouper(3, 'ABCDE', 'x')), [('A', 'B', 'C'), ('D', 'E', 'x')]) class RoundrobinTests(TestCase): """Tests for ``roundrobin()``""" def test_even_groups(self): """Ensure ordered output from evenly populated iterables""" eq_(list(roundrobin('ABC', [1, 2, 3], range(3))), ['A', 1, 0, 'B', 2, 1, 'C', 3, 2]) def test_uneven_groups(self): """Ensure ordered output from unevenly populated iterables""" eq_(list(roundrobin('ABCD', [1, 2], range(0))), ['A', 1, 'B', 2, 'C', 'D']) class PartitionTests(TestCase): """Tests for ``partition()``""" def test_bool(self): """Test when pred() returns a boolean""" lesser, greater = partition(lambda x: x > 5, range(10)) eq_(list(lesser), [0, 1, 2, 3, 4, 5]) eq_(list(greater), [6, 7, 8, 9]) def test_arbitrary(self): """Test when pred() returns an integer""" divisibles, remainders = partition(lambda x: x % 3, range(10)) eq_(list(divisibles), [0, 3, 6, 9]) eq_(list(remainders), [1, 2, 4, 5, 7, 8]) class PowersetTests(TestCase): """Tests for ``powerset()``""" def test_combinatorics(self): """Ensure a proper enumeration""" p = powerset([1, 2, 3]) eq_(list(p), [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]) class UniqueEverseenTests(TestCase): """Tests for ``unique_everseen()``""" def test_everseen(self): """ensure duplicate elements are ignored""" u = unique_everseen('AAAABBBBCCDAABBB') eq_(['A', 'B', 'C', 'D'], list(u)) def test_custom_key(self): """ensure the custom key comparison works""" u = unique_everseen('aAbACCc', key=str.lower) eq_(list('abC'), list(u)) def test_unhashable(self): """ensure things work for unhashable items""" iterable = ['a', [1, 2, 3], [1, 2, 3], 'a'] u = unique_everseen(iterable) eq_(list(u), ['a', [1, 2, 3]]) def test_unhashable_key(self): """ensure things work for unhashable items with a custom key""" iterable = ['a', [1, 2, 3], [1, 2, 3], 'a'] u = unique_everseen(iterable, key=lambda x: x) eq_(list(u), ['a', [1, 2, 3]]) class UniqueJustseenTests(TestCase): """Tests for ``unique_justseen()``""" def test_justseen(self): """ensure only last item is remembered""" u = unique_justseen('AAAABBBCCDABB') eq_(list('ABCDAB'), list(u)) def test_custom_key(self): """ensure the custom key comparison works""" u = unique_justseen('AABCcAD', str.lower) eq_(list('ABCAD'), list(u)) class IterExceptTests(TestCase): """Tests for ``iter_except()``""" def test_exact_exception(self): """ensure the exact specified exception is caught""" l = [1, 2, 3] i = iter_except(l.pop, IndexError) eq_(list(i), [3, 2, 1]) def test_generic_exception(self): """ensure the generic exception can be caught""" l = [1, 2] i = iter_except(l.pop, Exception) eq_(list(i), [2, 1]) def test_uncaught_exception_is_raised(self): """ensure a non-specified exception is raised""" l = [1, 2, 3] i = iter_except(l.pop, KeyError) assert_raises(IndexError, list, i) def test_first(self): """ensure first is run before the function""" l = [1, 2, 3] f = lambda: 25 i = iter_except(l.pop, IndexError, f) eq_(list(i), [25, 3, 2, 1]) class FirstTrueTests(TestCase): """Tests for ``first_true()``""" def test_something_true(self): """Test with no keywords""" eq_(first_true(range(10)), 1) def test_nothing_true(self): """Test default return value.""" eq_(first_true([0, 0, 0]), False) def test_default(self): """Test with a default keyword""" eq_(first_true([0, 0, 0], default='!'), '!') def test_pred(self): """Test with a custom predicate""" eq_(first_true([2, 4, 6], pred=lambda x: x % 3 == 0), 6) class RandomProductTests(TestCase): """Tests for ``random_product()`` Since random.choice() has different results with the same seed across python versions 2.x and 3.x, these tests use highly probably events to create predictable outcomes across platforms. """ def test_simple_lists(self): """Ensure that one item is chosen from each list in each pair. Also ensure that each item from each list eventually appears in the chosen combinations. Odds are roughly 1 in 7.1 * 10e16 that one item from either list will not be chosen after 100 samplings of one item from each list. Just to be safe, better use a known random seed, too. """ nums = [1, 2, 3] lets = ['a', 'b', 'c'] n, m = zip(*[random_product(nums, lets) for _ in range(100)]) n, m = set(n), set(m) eq_(n, set(nums)) eq_(m, set(lets)) eq_(len(n), len(nums)) eq_(len(m), len(lets)) def test_list_with_repeat(self): """ensure multiple items are chosen, and that they appear to be chosen from one list then the next, in proper order. """ nums = [1, 2, 3] lets = ['a', 'b', 'c'] r = list(random_product(nums, lets, repeat=100)) eq_(2 * 100, len(r)) n, m = set(r[::2]), set(r[1::2]) eq_(n, set(nums)) eq_(m, set(lets)) eq_(len(n), len(nums)) eq_(len(m), len(lets)) class RandomPermutationTests(TestCase): """Tests for ``random_permutation()``""" def test_full_permutation(self): """ensure every item from the iterable is returned in a new ordering 15 elements have a 1 in 1.3 * 10e12 of appearing in sorted order, so we fix a seed value just to be sure. """ i = range(15) r = random_permutation(i) eq_(set(i), set(r)) if i == r: raise AssertionError("Values were not permuted") def test_partial_permutation(self): """ensure all returned items are from the iterable, that the returned permutation is of the desired length, and that all items eventually get returned. Sampling 100 permutations of length 5 from a set of 15 leaves a (2/3)^100 chance that an item will not be chosen. Multiplied by 15 items, there is a 1 in 2.6e16 chance that at least 1 item will not show up in the resulting output. Using a random seed will fix that. """ items = range(15) item_set = set(items) all_items = set() for _ in range(100): permutation = random_permutation(items, 5) eq_(len(permutation), 5) permutation_set = set(permutation) ok_(permutation_set <= item_set) all_items |= permutation_set eq_(all_items, item_set) class RandomCombinationTests(TestCase): """Tests for ``random_combination()``""" def test_psuedorandomness(self): """ensure different subsets of the iterable get returned over many samplings of random combinations""" items = range(15) all_items = set() for _ in range(50): combination = random_combination(items, 5) all_items |= set(combination) eq_(all_items, set(items)) def test_no_replacement(self): """ensure that elements are sampled without replacement""" items = range(15) for _ in range(50): combination = random_combination(items, len(items)) eq_(len(combination), len(set(combination))) assert_raises(ValueError, random_combination, items, len(items) + 1) class RandomCombinationWithReplacementTests(TestCase): """Tests for ``random_combination_with_replacement()``""" def test_replacement(self): """ensure that elements are sampled with replacement""" items = range(5) combo = random_combination_with_replacement(items, len(items) * 2) eq_(2 * len(items), len(combo)) if len(set(combo)) == len(combo): raise AssertionError("Combination contained no duplicates") def test_psuedorandomness(self): """ensure different subsets of the iterable get returned over many samplings of random combinations""" items = range(15) all_items = set() for _ in range(50): combination = random_combination_with_replacement(items, 5) all_items |= set(combination) eq_(all_items, set(items)) more-itertools-3.2.0/more_itertools/tests/test_more.py0000664000175000017500000012413013117605216022312 0ustar bobo00000000000000from __future__ import division, print_function, unicode_literals from decimal import Decimal from fractions import Fraction from functools import reduce from io import StringIO from itertools import chain, count, groupby, permutations, product, repeat from operator import itemgetter from unittest import TestCase from nose.tools import eq_, assert_raises import six from six.moves import filter, range, zip from more_itertools import * # Test all the symbols are in __all__. class CollateTests(TestCase): """Unit tests for ``collate()``""" # Also accidentally tests peekable, though that could use its own tests def test_default(self): """Test with the default `key` function.""" iterables = [range(4), range(7), range(3, 6)] eq_(sorted(reduce(list.__add__, [list(it) for it in iterables])), list(collate(*iterables))) def test_key(self): """Test using a custom `key` function.""" iterables = [range(5, 0, -1), range(4, 0, -1)] actual = sorted( reduce(list.__add__, [list(it) for it in iterables]), reverse=True ) expected = list(collate(*iterables, key=lambda x: -x)) eq_(actual, expected) def test_empty(self): """Be nice if passed an empty list of iterables.""" eq_([], list(collate())) def test_one(self): """Work when only 1 iterable is passed.""" eq_([0, 1], list(collate(range(2)))) def test_reverse(self): """Test the `reverse` kwarg.""" iterables = [range(4, 0, -1), range(7, 0, -1), range(3, 6, -1)] eq_(sorted(reduce(list.__add__, [list(it) for it in iterables]), reverse=True), list(collate(*iterables, reverse=True))) class ChunkedTests(TestCase): """Tests for ``chunked()``""" def test_even(self): """Test when ``n`` divides evenly into the length of the iterable.""" eq_(list(chunked('ABCDEF', 3)), [['A', 'B', 'C'], ['D', 'E', 'F']]) def test_odd(self): """Test when ``n`` does not divide evenly into the length of the iterable. """ eq_(list(chunked('ABCDE', 3)), [['A', 'B', 'C'], ['D', 'E']]) class FirstTests(TestCase): """Tests for ``first()``""" def test_many(self): """Test that it works on many-item iterables.""" # Also try it on a generator expression to make sure it works on # whatever those return, across Python versions. eq_(first(x for x in range(4)), 0) def test_one(self): """Test that it doesn't raise StopIteration prematurely.""" eq_(first([3]), 3) def test_empty_stop_iteration(self): """It should raise StopIteration for empty iterables.""" assert_raises(ValueError, first, []) def test_default(self): """It should return the provided default arg for empty iterables.""" eq_(first([], 'boo'), 'boo') class PeekableTests(TestCase): """Tests for ``peekable()`` behavor not incidentally covered by testing ``collate()`` """ def test_peek_default(self): """Make sure passing a default into ``peek()`` works.""" p = peekable([]) eq_(p.peek(7), 7) def test_truthiness(self): """Make sure a ``peekable`` tests true iff there are items remaining in the iterable. """ p = peekable([]) self.assertFalse(p) p = peekable(range(3)) self.assertTrue(p) def test_simple_peeking(self): """Make sure ``next`` and ``peek`` advance and don't advance the iterator, respectively. """ p = peekable(range(10)) eq_(next(p), 0) eq_(p.peek(), 1) eq_(next(p), 1) def test_indexing(self): """ Indexing into the peekable shouldn't advance the iterator. """ p = peekable('abcdefghijkl') # The 0th index is what ``next()`` will return eq_(p[0], 'a') eq_(next(p), 'a') # Indexing further into the peekable shouldn't advance the itertor eq_(p[2], 'd') eq_(next(p), 'b') # The 0th index moves up with the iterator; the last index follows eq_(p[0], 'c') eq_(p[9], 'l') eq_(next(p), 'c') eq_(p[8], 'l') # Negative indexing should work too eq_(p[-2], 'k') eq_(p[-9], 'd') self.assertRaises(IndexError, lambda: p[-10]) def test_slicing(self): """Slicing the peekable shouldn't advance the iterator.""" seq = list('abcdefghijkl') p = peekable(seq) # Slicing the peekable should just be like slicing a re-iterable eq_(p[1:4], seq[1:4]) # Advancing the iterator moves the slices up also eq_(next(p), 'a') eq_(p[1:4], seq[1:][1:4]) # Implicit starts and stop should work eq_(p[:5], seq[1:][:5]) eq_(p[:], seq[1:][:]) # Indexing past the end should work eq_(p[:100], seq[1:][:100]) # Steps should work, including negative eq_(p[::2], seq[1:][::2]) eq_(p[::-1], seq[1:][::-1]) def test_slicing_reset(self): """Test slicing on a fresh iterable each time""" iterable = ['0', '1', '2', '3', '4', '5'] indexes = list(range(-4, len(iterable) + 4)) + [None] steps = [1, 2, 3, 4, -1, -2, -3, 4] for slice_args in product(indexes, indexes, steps): it = iter(iterable) p = peekable(it) next(p) index = slice(*slice_args) actual = p[index] expected = iterable[1:][index] self.assertEqual(actual, expected, slice_args) def test_slicing_error(self): iterable = '01234567' p = peekable(iter(iterable)) # Prime the cache p.peek() old_cache = list(p._cache) # Illegal slice with self.assertRaises(ValueError): p[1:-1:0] # Neither the cache nor the iteration should be affected self.assertEqual(old_cache, list(p._cache)) self.assertEqual(list(p), list(iterable)) def test_passthrough(self): """Iterating a peekable without using ``peek()`` or ``prepend()`` should just give the underlying iterable's elements (a trivial test but useful to set a baseline in case something goes wrong)""" expected = [1, 2, 3, 4, 5] actual = list(peekable(expected)) eq_(actual, expected) # prepend() behavior tests def test_prepend(self): """Tests intersperesed ``prepend()`` and ``next()`` calls""" it = peekable(range(2)) actual = [] # Test prepend() before next() it.prepend(10) actual += [next(it), next(it)] # Test prepend() between next()s it.prepend(11) actual += [next(it), next(it)] # Test prepend() after source iterable is consumed it.prepend(12) actual += [next(it)] expected = [10, 0, 11, 1, 12] eq_(actual, expected) def test_multi_prepend(self): """Tests prepending multiple items and getting them in proper order""" it = peekable(range(5)) actual = [next(it), next(it)] it.prepend(10, 11, 12) it.prepend(20, 21) actual += list(it) expected = [0, 1, 20, 21, 10, 11, 12, 2, 3, 4] eq_(actual, expected) def test_empty(self): """Tests prepending in front of an empty iterable""" it = peekable([]) it.prepend(10) actual = list(it) expected = [10] eq_(actual, expected) def test_prepend_truthiness(self): """Tests that ``__bool__()`` or ``__nonzero__()`` works properly with ``prepend()``""" it = peekable(range(5)) self.assertTrue(it) actual = list(it) self.assertFalse(it) it.prepend(10) self.assertTrue(it) actual += [next(it)] self.assertFalse(it) expected = [0, 1, 2, 3, 4, 10] eq_(actual, expected) def test_multi_prepend_peek(self): """Tests prepending multiple elements and getting them in reverse order while peeking""" it = peekable(range(5)) actual = [next(it), next(it)] eq_(it.peek(), 2) it.prepend(10, 11, 12) eq_(it.peek(), 10) it.prepend(20, 21) eq_(it.peek(), 20) actual += list(it) self.assertFalse(it) expected = [0, 1, 20, 21, 10, 11, 12, 2, 3, 4] eq_(actual, expected) def test_prepend_after_stop(self): """Test resuming iteration after a previous exhaustion""" it = peekable(range(3)) eq_(list(it), [0, 1, 2]) self.assertRaises(StopIteration, lambda: next(it)) it.prepend(10) eq_(next(it), 10) self.assertRaises(StopIteration, lambda: next(it)) def test_prepend_slicing(self): """Tests interaction between prepending and slicing""" seq = list(range(20)) p = peekable(seq) p.prepend(30, 40, 50) pseq = [30, 40, 50] + seq # pseq for prepended_seq # adapt the specific tests from test_slicing eq_(p[0], 30) eq_(p[1:8], pseq[1:8]) eq_(p[1:], pseq[1:]) eq_(p[:5], pseq[:5]) eq_(p[:], pseq[:]) eq_(p[:100], pseq[:100]) eq_(p[::2], pseq[::2]) eq_(p[::-1], pseq[::-1]) def test_prepend_indexing(self): """Tests interaction between prepending and indexing""" seq = list(range(20)) p = peekable(seq) p.prepend(30, 40, 50) eq_(p[0], 30) eq_(next(p), 30) eq_(p[2], 0) eq_(next(p), 40) eq_(p[0], 50) eq_(p[9], 8) eq_(next(p), 50) eq_(p[8], 8) eq_(p[-2], 18) eq_(p[-9], 11) self.assertRaises(IndexError, lambda: p[-21]) def test_prepend_iterable(self): """Tests prepending from an iterable""" it = peekable(range(5)) # Don't directly use the range() object to avoid any range-specific # optimizations it.prepend(*(x for x in range(5))) actual = list(it) expected = list(chain(range(5), range(5))) eq_(actual, expected) def test_prepend_many(self): """Tests that prepending a huge number of elements works""" it = peekable(range(5)) # Don't directly use the range() object to avoid any range-specific # optimizations it.prepend(*(x for x in range(20000))) actual = list(it) expected = list(chain(range(20000), range(5))) eq_(actual, expected) def test_prepend_reversed(self): """Tests prepending from a reversed iterable""" it = peekable(range(3)) it.prepend(*reversed((10, 11, 12))) actual = list(it) expected = [12, 11, 10, 0, 1, 2] eq_(actual, expected) class ConsumerTests(TestCase): """Tests for ``consumer()``""" def test_consumer(self): @consumer def eater(): while True: x = yield e = eater() e.send('hi') # without @consumer, would raise TypeError def test_distinct_permutations(): """Make sure the output for ``distinct_permutations()`` is the same as set(permutations(it)). """ iterable = ['z', 'a', 'a', 'q', 'q', 'q', 'y'] test_output = sorted(distinct_permutations(iterable)) ref_output = sorted(set(permutations(iterable))) eq_(test_output, ref_output) def test_ilen(): """Sanity-checks for ``ilen()``.""" # Non-empty eq_(ilen(filter(lambda x: x % 10 == 0, range(101))), 11) # Empty eq_(ilen((x for x in range(0))), 0) # Iterable with __len__ eq_(ilen(list(range(6))), 6) def test_with_iter(): """Make sure ``with_iter`` iterates over and closes things correctly.""" s = StringIO('One fish\nTwo fish') initial_words = [line.split()[0] for line in with_iter(s)] # Iterable's items should be faithfully represented eq_(initial_words, ['One', 'Two']) # The file object should be closed eq_(s.closed, True) def test_one(): """Test the ``one()`` cases that aren't covered by its doctests.""" # Infinite iterables numbers = count() assert_raises(ValueError, one, numbers) # burn 0 and 1 eq_(next(numbers), 2) class IntersperseTest(TestCase): """ Tests for intersperse() """ def test_even(self): eq_(list(intersperse(None, '01')), ['0', None, '1']) def test_odd(self): eq_(list(intersperse(None, '012')), ['0', None, '1', None, '2']) def test_generator(self): iterable = (x for x in '012') eq_(list(intersperse(None, iterable)), ['0', None, '1', None, '2']) def test_intersperse_not_iterable(self): assert_raises(TypeError, lambda: intersperse('x', 1)) class UniqueToEachTests(TestCase): """Tests for ``unique_to_each()``""" def test_all_unique(self): """When all the input iterables are unique the output should match the input.""" iterables = [[1, 2], [3, 4, 5], [6, 7, 8]] eq_(unique_to_each(*iterables), iterables) def test_duplicates(self): """When there are duplicates in any of the input iterables that aren't in the rest, those duplicates should be emitted.""" iterables = ["mississippi", "missouri"] eq_(unique_to_each(*iterables), [['p', 'p'], ['o', 'u', 'r']]) def test_mixed(self): """When the input iterables contain different types the function should still behave properly""" iterables = ['x', (i for i in range(3)), [1, 2, 3], tuple()] eq_(unique_to_each(*iterables), [['x'], [0], [3], []]) class WindowedTests(TestCase): """Tests for ``windowed()``""" def test_basic(self): actual = list(windowed([1, 2, 3, 4, 5], 3)) expected = [(1, 2, 3), (2, 3, 4), (3, 4, 5)] eq_(actual, expected) def test_large_size(self): """ When the window size is larger than the iterable, and no fill value is given,``None`` should be filled in. """ actual = list(windowed([1, 2, 3, 4, 5], 6)) expected = [(1, 2, 3, 4, 5, None)] eq_(actual, expected) def test_fillvalue(self): """ When sizes don't match evenly, the given fill value should be used. """ iterable = [1, 2, 3, 4, 5] for n, kwargs, expected in [ (6, {}, [(1, 2, 3, 4, 5, '!')]), # n > len(iterable) (3, {'step': 3}, [(1, 2, 3), (4, 5, '!')]), # using ``step`` ]: actual = list(windowed(iterable, n, fillvalue='!', **kwargs)) eq_(actual, expected) def test_zero(self): """When the window size is zero, an empty tuple should be emitted.""" actual = list(windowed([1, 2, 3, 4, 5], 0)) expected = [tuple()] eq_(actual, expected) def test_negative(self): """When the window size is negative, ValueError should be raised.""" with self.assertRaises(ValueError): list(windowed([1, 2, 3, 4, 5], -1)) def test_step(self): """The window should advance by the number of steps provided""" iterable = [1, 2, 3, 4, 5, 6, 7] for n, step, expected in [ (3, 2, [(1, 2, 3), (3, 4, 5), (5, 6, 7)]), # n > step (3, 3, [(1, 2, 3), (4, 5, 6), (7, None, None)]), # n == step (3, 4, [(1, 2, 3), (5, 6, 7)]), # line up nicely (3, 5, [(1, 2, 3), (6, 7, None)]), # off by one (3, 6, [(1, 2, 3), (7, None, None)]), # off by two (3, 7, [(1, 2, 3)]), # step past the end (7, 8, [(1, 2, 3, 4, 5, 6, 7)]), # step > len(iterable) ]: actual = list(windowed(iterable, n, step=step)) eq_(actual, expected) # Step must be greater than or equal to 1 with self.assertRaises(ValueError): list(windowed(iterable, 3, step=0)) class BucketTests(TestCase): """Tests for ``bucket()``""" def test_basic(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] D = bucket(iterable, key=lambda x: 10 * (x // 10)) # In-order access eq_(list(D[10]), [10, 11, 12]) # Out of order access eq_(list(D[30]), [30, 31, 33]) eq_(list(D[20]), [20, 21, 22, 23]) eq_(list(D[40]), []) # Nothing in here! def test_in(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] D = bucket(iterable, key=lambda x: 10 * (x // 10)) self.assertTrue(10 in D) self.assertFalse(40 in D) self.assertTrue(20 in D) self.assertFalse(21 in D) # Checking in-ness shouldn't advance the iterator eq_(next(D[10]), 10) class SpyTests(TestCase): """Tests for ``spy()``""" def test_basic(self): original_iterable = iter('abcdefg') head, new_iterable = spy(original_iterable) eq_(head, ['a']) eq_(list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']) def test_unpacking(self): original_iterable = iter('abcdefg') (first, second, third), new_iterable = spy(original_iterable, 3) eq_(first, 'a') eq_(second, 'b') eq_(third, 'c') eq_(list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']) def test_too_many(self): original_iterable = iter('abc') head, new_iterable = spy(original_iterable, 4) eq_(head, ['a', 'b', 'c']) eq_(list(new_iterable), ['a', 'b', 'c']) def test_zero(self): original_iterable = iter('abc') head, new_iterable = spy(original_iterable, 0) eq_(head, []) eq_(list(new_iterable), ['a', 'b', 'c']) class TestInterleave(TestCase): """Tests for ``interleave()`` and ``interleave_longest()``""" def test_interleave(self): l = [[1, 2, 3], [4, 5], [6, 7, 8]] eq_(list(interleave(*l)), [1, 4, 6, 2, 5, 7]) l = [[1, 2], [3, 4, 5], [6, 7, 8]] eq_(list(interleave(*l)), [1, 3, 6, 2, 4, 7]) l = [[1, 2, 3], [4, 5, 6], [7, 8]] eq_(list(interleave(*l)), [1, 4, 7, 2, 5, 8]) def test_interleave_longest(self): l = [[1, 2, 3], [4, 5], [6, 7, 8]] eq_(list(interleave_longest(*l)), [1, 4, 6, 2, 5, 7, 3, 8]) l = [[1, 2], [3, 4, 5], [6, 7, 8]] eq_(list(interleave_longest(*l)), [1, 3, 6, 2, 4, 7, 5, 8]) l = [[1, 2, 3], [4, 5, 6], [7, 8]] eq_(list(interleave_longest(*l)), [1, 4, 7, 2, 5, 8, 3, 6]) class TestCollapse(TestCase): """Tests for ``collapse()``""" def test_collapse(self): l = [[1], 2, [[3], 4], [[[5]]]] eq_(list(collapse(l)), [1, 2, 3, 4, 5]) def test_collapse_to_string(self): l = [["s1"], "s2", [["s3"], "s4"], [[["s5"]]]] eq_(list(collapse(l)), ["s1", "s2", "s3", "s4", "s5"]) def test_collapse_flatten(self): l = [[1], [2], [[3], 4], [[[5]]]] eq_(list(collapse(l, levels=1)), list(flatten(l))) def test_collapse_to_level(self): l = [[1], 2, [[3], 4], [[[5]]]] eq_(list(collapse(l, levels=2)), [1, 2, 3, 4, [5]]) eq_(list(collapse(collapse(l, levels=1), levels=1)), list(collapse(l, levels=2))) def test_collapse_to_list(self): l = (1, [2], (3, [4, (5,)], 'ab')) actual = list(collapse(l, base_type=list)) expected = [1, [2], 3, [4, (5,)], 'ab'] eq_(actual, expected) class SideEffectTests(TestCase): """Tests for ``side_effect()``""" def test_individual(self): # The function increments the counter for each call counter = [0] def func(arg): counter[0] += 1 result = list(side_effect(func, range(10))) eq_(result, list(range(10))) eq_(counter[0], 10) def test_chunked(self): # The function increments the counter for each call counter = [0] def func(arg): counter[0] += 1 result = list(side_effect(func, range(10), 2)) eq_(result, list(range(10))) eq_(counter[0], 5) def test_before_after(self): f = StringIO() collector = [] def func(item): print(item, file=f) collector.append(f.getvalue()) def it(): yield u'a' yield u'b' raise Exception('kaboom') before = lambda: print('HEADER', file=f) after = f.close try: consume(side_effect(func, it(), before=before, after=after)) except Exception: pass # The iterable should have been written to the file self.assertEqual(collector, [u'HEADER\na\n', u'HEADER\na\nb\n']) # The file should be closed even though something bad happened self.assertTrue(f.closed) def test_before_fails(self): f = StringIO() func = lambda x: print(x, file=f) def before(): raise Exception('ouch') try: consume(side_effect(func, u'abc', before=before, after=f.close)) except Exception: pass # The file should be closed even though something bad happened in the # before function self.assertTrue(f.closed) class SlicedTests(TestCase): """Tests for ``sliced()``""" def test_even(self): """Test when the length of the sequence is divisible by *n*""" seq = 'ABCDEFGHI' eq_(list(sliced(seq, 3)), ['ABC', 'DEF', 'GHI']) def test_odd(self): """Test when the length of the sequence is not divisible by *n*""" seq = 'ABCDEFGHI' eq_(list(sliced(seq, 4)), ['ABCD', 'EFGH', 'I']) def test_not_sliceable(self): seq = (x for x in 'ABCDEFGHI') with self.assertRaises(TypeError): list(sliced(seq, 3)) class SplitBeforeTest(TestCase): """Tests for ``split_before()``""" def test_starts_with_sep(self): actual = list(split_before('xooxoo', lambda c: c == 'x')) expected = [['x', 'o', 'o'], ['x', 'o', 'o']] eq_(actual, expected) def test_ends_with_sep(self): actual = list(split_before('ooxoox', lambda c: c == 'x')) expected = [['o', 'o'], ['x', 'o', 'o'], ['x']] eq_(actual, expected) def test_no_sep(self): actual = list(split_before('ooo', lambda c: c == 'x')) expected = [['o', 'o', 'o']] eq_(actual, expected) class SplitAfterTest(TestCase): """Tests for ``split_after()``""" def test_starts_with_sep(self): actual = list(split_after('xooxoo', lambda c: c == 'x')) expected = [['x'], ['o', 'o', 'x'], ['o', 'o']] eq_(actual, expected) def test_ends_with_sep(self): actual = list(split_after('ooxoox', lambda c: c == 'x')) expected = [['o', 'o', 'x'], ['o', 'o', 'x']] eq_(actual, expected) def test_no_sep(self): actual = list(split_after('ooo', lambda c: c == 'x')) expected = [['o', 'o', 'o']] eq_(actual, expected) class PaddedTest(TestCase): """Tests for ``padded()``""" def test_no_n(self): seq = [1, 2, 3] # No fillvalue self.assertEqual(take(5, padded(seq)), [1, 2, 3, None, None]) # With fillvalue self.assertEqual(take(5, padded(seq, fillvalue='')), [1, 2, 3, '', '']) def test_invalid_n(self): self.assertRaises(ValueError, lambda: list(padded([1, 2, 3], n=-1))) self.assertRaises(ValueError, lambda: list(padded([1, 2, 3], n=0))) def test_valid_n(self): seq = [1, 2, 3, 4, 5] # No need for padding: len(seq) <= n self.assertEqual(list(padded(seq, n=4)), [1, 2, 3, 4, 5]) self.assertEqual(list(padded(seq, n=5)), [1, 2, 3, 4, 5]) # No fillvalue self.assertEqual(list(padded(seq, n=7)), [1, 2, 3, 4, 5, None, None]) # With fillvalue self.assertEqual( list(padded(seq, fillvalue='', n=7)), [1, 2, 3, 4, 5, '', ''] ) def test_next_multiple(self): seq = [1, 2, 3, 4, 5, 6] # No need for padding: len(seq) % n == 0 self.assertEqual( list(padded(seq, n=3, next_multiple=True)), [1, 2, 3, 4, 5, 6] ) # Padding needed: len(seq) < n self.assertEqual( list(padded(seq, n=8, next_multiple=True)), [1, 2, 3, 4, 5, 6, None, None] ) # No padding needed: len(seq) == n self.assertEqual( list(padded(seq, n=6, next_multiple=True)), [1, 2, 3, 4, 5, 6] ) # Padding needed: len(seq) > n self.assertEqual( list(padded(seq, n=4, next_multiple=True)), [1, 2, 3, 4, 5, 6, None, None] ) # With fillvalue self.assertEqual( list(padded(seq, fillvalue='', n=4, next_multiple=True)), [1, 2, 3, 4, 5, 6, '', ''] ) class DistributeTest(TestCase): """Tests for distribute()""" def test_invalid_n(self): self.assertRaises(ValueError, lambda: distribute(-1, [1, 2, 3])) self.assertRaises(ValueError, lambda: distribute(0, [1, 2, 3])) def test_basic(self): iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for n, expected in [ (1, [iterable]), (2, [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]), (3, [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]), (10, [[n] for n in range(1, 10 + 1)]), ]: eq_([list(x) for x in distribute(n, iterable)], expected) def test_large_n(self): iterable = [1, 2, 3, 4] eq_( [list(x) for x in distribute(6, iterable)], [[1], [2], [3], [4], [], []] ) class StaggerTest(TestCase): """Tests for ``stagger()``""" def test_default(self): iterable = [0, 1, 2, 3] actual = list(stagger(iterable)) expected = [(None, 0, 1), (0, 1, 2), (1, 2, 3)] eq_(actual, expected) def test_offsets(self): iterable = [0, 1, 2, 3] for offsets, expected in [ ((-2, 0, 2), [('', 0, 2), ('', 1, 3)]), ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3)]), ((1, 2), [(1, 2), (2, 3)]), ]: all_groups = stagger(iterable, offsets=offsets, fillvalue='') eq_(list(all_groups), expected) def test_longest(self): iterable = [0, 1, 2, 3] for offsets, expected in [ ( (-1, 0, 1), [('', 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, ''), (3, '', '')] ), ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3), (3, '')]), ((1, 2), [(1, 2), (2, 3), (3, '')]), ]: all_groups = stagger( iterable, offsets=offsets, fillvalue='', longest=True ) eq_(list(all_groups), expected) class ZipOffsetTest(TestCase): """Tests for ``zip_offset()``""" def test_shortest(self): seq_1 = [0, 1, 2, 3] seq_2 = [0, 1, 2, 3, 4, 5] seq_3 = [0, 1, 2, 3, 4, 5, 6, 7] actual = list( zip_offset(seq_1, seq_2, seq_3, offsets=(-1, 0, 1), fillvalue='') ) expected = [('', 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)] eq_(actual, expected) def test_longest(self): seq_1 = [0, 1, 2, 3] seq_2 = [0, 1, 2, 3, 4, 5] seq_3 = [0, 1, 2, 3, 4, 5, 6, 7] actual = list( zip_offset(seq_1, seq_2, seq_3, offsets=(-1, 0, 1), longest=True) ) expected = [ (None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (None, 5, 6), (None, None, 7), ] eq_(actual, expected) def test_mismatch(self): iterables = [0, 1, 2], [2, 3, 4] offsets = (-1, 0, 1) self.assertRaises( ValueError, lambda: list(zip_offset(*iterables, offsets=offsets)) ) class SortTogetherTest(TestCase): """Tests for sort_together()""" def test_key_list(self): """tests `key_list` including default, iterables include duplicates""" iterables = [['GA', 'GA', 'GA', 'CT', 'CT', 'CT'], ['May', 'Aug.', 'May', 'June', 'July', 'July'], [97, 20, 100, 70, 100, 20]] eq_(sort_together(iterables), [('CT', 'CT', 'CT', 'GA', 'GA', 'GA'), ('June', 'July', 'July', 'May', 'Aug.', 'May'), (70, 100, 20, 97, 20, 100)]) eq_(sort_together(iterables, key_list=(0, 1)), [('CT', 'CT', 'CT', 'GA', 'GA', 'GA'), ('July', 'July', 'June', 'Aug.', 'May', 'May'), (100, 20, 70, 20, 97, 100)]) eq_(sort_together(iterables, key_list=(0, 1, 2)), [('CT', 'CT', 'CT', 'GA', 'GA', 'GA'), ('July', 'July', 'June', 'Aug.', 'May', 'May'), (20, 100, 70, 20, 97, 100)]) eq_(sort_together(iterables, key_list=(2,)), [('GA', 'CT', 'CT', 'GA', 'GA', 'CT'), ('Aug.', 'July', 'June', 'May', 'May', 'July'), (20, 20, 70, 97, 100, 100)]) def test_invalid_key_list(self): """tests `key_list` for indexes not available in `iterables`""" iterables = [['GA', 'GA', 'GA', 'CT', 'CT', 'CT'], ['May', 'Aug.', 'May', 'June', 'July', 'July'], [97, 20, 100, 70, 100, 20]] self.assertRaises(IndexError, lambda: sort_together(iterables, key_list=(5,))) def test_reverse(self): """tests `reverse` to ensure a reverse sort for `key_list` iterables""" iterables = [['GA', 'GA', 'GA', 'CT', 'CT', 'CT'], ['May', 'Aug.', 'May', 'June', 'July', 'July'], [97, 20, 100, 70, 100, 20]] eq_(sort_together(iterables, key_list=(0, 1, 2), reverse=True), [('GA', 'GA', 'GA', 'CT', 'CT', 'CT'), ('May', 'May', 'Aug.', 'June', 'July', 'July'), (100, 97, 20, 70, 100, 20)]) def test_uneven_iterables(self): """tests trimming of iterables to the shortest length before sorting""" iterables = [['GA', 'GA', 'GA', 'CT', 'CT', 'CT', 'MA'], ['May', 'Aug.', 'May', 'June', 'July', 'July'], [97, 20, 100, 70, 100, 20, 0]] eq_(sort_together(iterables), [('CT', 'CT', 'CT', 'GA', 'GA', 'GA'), ('June', 'July', 'July', 'May', 'Aug.', 'May'), (70, 100, 20, 97, 20, 100)]) class DivideTest(TestCase): """Tests for divide()""" def test_invalid_n(self): self.assertRaises(ValueError, lambda: divide(-1, [1, 2, 3])) self.assertRaises(ValueError, lambda: divide(0, [1, 2, 3])) def test_basic(self): iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for n, expected in [ (1, [iterable]), (2, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]), (3, [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]), (10, [[n] for n in range(1, 10 + 1)]), ]: eq_([list(x) for x in divide(n, iterable)], expected) def test_large_n(self): iterable = [1, 2, 3, 4] eq_( [list(x) for x in divide(6, iterable)], [[1], [2], [3], [4], [], []] ) class TestAlwaysIterable(TestCase): """Tests for always_iterable()""" def test_single(self): self.assertEqual(always_iterable(1), (1,)) self.assertEqual(list(always_iterable(1)), [1]) def test_strings(self): self.assertEqual(always_iterable('foo'), ('foo',)) self.assertEqual(always_iterable(six.b('bar')), (six.b('bar'),)) self.assertEqual(always_iterable(six.u(b'baz')), (six.u(b'baz'),)) def test_iterables(self): self.assertEqual(always_iterable([0, 1]), [0, 1]) self.assertEqual(list(iter('foo')), ['f', 'o', 'o']) self.assertEqual(list([]), []) def test_none(self): self.assertEqual(always_iterable(None), ()) self.assertEqual(list(always_iterable(None)), []) def test_generator(self): def _gen(): yield 0 yield 1 self.assertEqual(list(always_iterable(_gen())), [0, 1]) class AdjacentTests(TestCase): def test_typical(self): actual = list(adjacent(lambda x: x % 5 == 0, range(10))) expected = [(True, 0), (True, 1), (False, 2), (False, 3), (True, 4), (True, 5), (True, 6), (False, 7), (False, 8), (False, 9)] self.assertEqual(actual, expected) def test_empty_iterable(self): actual = list(adjacent(lambda x: x % 5 == 0, [])) expected = [] self.assertEqual(actual, expected) def test_length_one(self): actual = list(adjacent(lambda x: x % 5 == 0, [0])) expected = [(True, 0)] self.assertEqual(actual, expected) actual = list(adjacent(lambda x: x % 5 == 0, [1])) expected = [(False, 1)] self.assertEqual(actual, expected) def test_consecutive_true(self): """Test that when the predicate matches multiple consecutive elements it doesn't repeat elements in the output""" actual = list(adjacent(lambda x: x % 5 < 2, range(10))) expected = [(True, 0), (True, 1), (True, 2), (False, 3), (True, 4), (True, 5), (True, 6), (True, 7), (False, 8), (False, 9)] self.assertEqual(actual, expected) def test_distance(self): actual = list(adjacent(lambda x: x % 5 == 0, range(10), distance=2)) expected = [(True, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5), (True, 6), (True, 7), (False, 8), (False, 9)] self.assertEqual(actual, expected) actual = list(adjacent(lambda x: x % 5 == 0, range(10), distance=3)) expected = [(True, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5), (True, 6), (True, 7), (True, 8), (False, 9)] self.assertEqual(actual, expected) def test_large_distance(self): """Test distance larger than the length of the iterable""" iterable = range(10) actual = list(adjacent(lambda x: x % 5 == 4, iterable, distance=20)) expected = list(zip(repeat(True), iterable)) self.assertEqual(actual, expected) actual = list(adjacent(lambda x: False, iterable, distance=20)) expected = list(zip(repeat(False), iterable)) self.assertEqual(actual, expected) def test_zero_distance(self): """Test that adjacent() reduces to zip+map when distance is 0""" iterable = range(1000) predicate = lambda x: x % 4 == 2 actual = adjacent(predicate, iterable, 0) expected = zip(map(predicate, iterable), iterable) self.assertTrue(all(a == e for a, e in zip(actual, expected))) def test_negative_distance(self): """Test that adjacent() raises an error with negative distance""" pred = lambda x: x self.assertRaises(ValueError, lambda: adjacent(pred, range(1000), -1)) self.assertRaises(ValueError, lambda: adjacent(pred, range(10), -10)) def test_grouping(self): """Test interaction of adjacent() with groupby_transform()""" iterable = adjacent(lambda x: x % 5 == 0, range(10)) grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1)) actual = [(k, list(g)) for k, g in grouper] expected = [ (True, [0, 1]), (False, [2, 3]), (True, [4, 5, 6]), (False, [7, 8, 9]), ] self.assertEqual(actual, expected) def test_call_once(self): """Test that the predicate is only called once per item.""" already_seen = set() iterable = range(10) def predicate(item): self.assertNotIn(item, already_seen) already_seen.add(item) return True actual = list(adjacent(predicate, iterable)) expected = [(True, x) for x in iterable] self.assertEqual(actual, expected) class GroupByTransformTests(TestCase): def assertAllGroupsEqual(self, groupby1, groupby2): """Compare two groupby objects for equality, both keys and groups.""" for a, b in zip(groupby1, groupby2): key1, group1 = a key2, group2 = b self.assertEqual(key1, key2) self.assertListEqual(list(group1), list(group2)) self.assertRaises(StopIteration, lambda: next(groupby1)) self.assertRaises(StopIteration, lambda: next(groupby2)) def test_default_funcs(self): """Test that groupby_transform() with default args mimics groupby()""" iterable = [(x // 5, x) for x in range(1000)] actual = groupby_transform(iterable) expected = groupby(iterable) self.assertAllGroupsEqual(actual, expected) def test_valuefunc(self): iterable = [(int(x / 5), int(x / 3), x) for x in range(10)] # Test the standard usage of grouping one iterable using another's keys grouper = groupby_transform( iterable, keyfunc=itemgetter(0), valuefunc=itemgetter(-1) ) actual = [(k, list(g)) for k, g in grouper] expected = [(0, [0, 1, 2, 3, 4]), (1, [5, 6, 7, 8, 9])] self.assertEqual(actual, expected) grouper = groupby_transform( iterable, keyfunc=itemgetter(1), valuefunc=itemgetter(-1) ) actual = [(k, list(g)) for k, g in grouper] expected = [(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])] self.assertEqual(actual, expected) # and now for something a little different d = dict(zip(range(10), 'abcdefghij')) grouper = groupby_transform( range(10), keyfunc=lambda x: x // 5, valuefunc=d.get ) actual = [(k, ''.join(g)) for k, g in grouper] expected = [(0, 'abcde'), (1, 'fghij')] self.assertEqual(actual, expected) def test_no_valuefunc(self): iterable = range(1000) def key(x): return x // 5 actual = groupby_transform(iterable, key, valuefunc=None) expected = groupby(iterable, key) self.assertAllGroupsEqual(actual, expected) actual = groupby_transform(iterable, key) # default valuefunc expected = groupby(iterable, key) self.assertAllGroupsEqual(actual, expected) class ArithmeticSequenceTests(TestCase): def test_basic(self): for args, expected in [ ((4,), [0, 1, 2, 3]), ((4.0,), [0.0, 1.0, 2.0, 3.0]), ((1.0, 4), [1.0, 2.0, 3.0]), ((1, 4.0), [1, 2, 3]), ((1.0, 5), [1.0, 2.0, 3.0, 4.0]), ((0, 20, 5), [0, 5, 10, 15]), ((0, 20, 5.0), [0.0, 5.0, 10.0, 15.0]), ((0, 10, 3), [0, 3, 6, 9]), ((0, 10, 3.0), [0.0, 3.0, 6.0, 9.0]), ((0, -5, -1), [0, -1, -2, -3, -4]), ((0.0, -5, -1), [0.0, -1.0, -2.0, -3.0, -4.0]), ((1, 2, Fraction(1, 2)), [Fraction(1, 1), Fraction(3, 2)]), ((0,), []), ((0.0,), []), ((1, 0), []), ((1.0, 0.0), []), ((Fraction(2, 1),), [Fraction(0, 1), Fraction(1, 1)]), ((Decimal('2.0'),), [Decimal('0.0'), Decimal('1.0')]), ]: actual = list(numeric_range(*args)) self.assertEqual(actual, expected) self.assertTrue( all(type(a) == type(e) for a, e in zip(actual, expected)) ) def test_arg_count(self): self.assertRaises(TypeError, lambda: list(numeric_range())) self.assertRaises( TypeError, lambda: list(numeric_range(0, 1, 2, 3)) ) def test_zero_step(self): self.assertRaises( ValueError, lambda: list(numeric_range(1, 2, 0)) ) class CountCycleTests(TestCase): def test_basic(self): expected = [ (0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), ] for actual in [ take(9, count_cycle('abc')), # n=None list(count_cycle('abc', 3)), # n=3 ]: self.assertEqual(actual, expected) def test_empty(self): self.assertEqual(list(count_cycle('')), []) self.assertEqual(list(count_cycle('', 2)), []) def test_negative(self): self.assertEqual(list(count_cycle('abc', -3)), []) class LocateTests(TestCase): def test_default_pred(self): iterable = [0, 1, 1, 0, 1, 0, 0] actual = list(locate(iterable)) expected = [1, 2, 4] self.assertEqual(actual, expected) def test_no_matches(self): iterable = [0, 0, 0] actual = list(locate(iterable)) expected = [] self.assertEqual(actual, expected) def test_custom_pred(self): iterable = ['0', 1, 1, '0', 1, '0', '0'] pred = lambda x: x == '0' actual = list(locate(iterable, pred)) expected = [0, 3, 5, 6] self.assertEqual(actual, expected) class StripFunctionTests(TestCase): def test_hashable(self): iterable = list('www.example.com') pred = lambda x: x in set('cmowz.') self.assertEqual(list(lstrip(iterable, pred)), list('example.com')) self.assertEqual(list(rstrip(iterable, pred)), list('www.example')) self.assertEqual(list(strip(iterable, pred)), list('example')) def test_not_hashable(self): iterable = [ list('http://'), list('www'), list('.example'), list('.com') ] pred = lambda x: x in [list('http://'), list('www'), list('.com')] self.assertEqual(list(lstrip(iterable, pred)), iterable[2:]) self.assertEqual(list(rstrip(iterable, pred)), iterable[:3]) self.assertEqual(list(strip(iterable, pred)), iterable[2: 3]) def test_math(self): iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] pred = lambda x: x <= 2 self.assertEqual(list(lstrip(iterable, pred)), iterable[3:]) self.assertEqual(list(rstrip(iterable, pred)), iterable[:-3]) self.assertEqual(list(strip(iterable, pred)), iterable[3:-3]) class IsliceExtendedTests(TestCase): def test_all(self): iterable = ['0', '1', '2', '3', '4', '5'] indexes = list(range(-4, len(iterable) + 4)) + [None] steps = [1, 2, 3, 4, -1, -2, -3, 4] for slice_args in product(indexes, indexes, steps): try: actual = list(islice_extended(iterable, *slice_args)) except Exception as e: self.fail((slice_args, e)) expected = iterable[slice(*slice_args)] self.assertEqual(actual, expected, slice_args) def test_zero_step(self): with self.assertRaises(ValueError): list(islice_extended([1, 2, 3], 0, 1, 0)) more-itertools-3.2.0/setup.py0000664000175000017500000000345013117606234015243 0ustar bobo00000000000000# Hack to prevent stupid error on exit of `python setup.py test`. (See # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html.) try: import multiprocessing except ImportError: pass from re import sub from setuptools import setup, find_packages setup( name='more-itertools', version='3.2.0', description='More routines for operating on iterables, beyond itertools', long_description=open('README.rst').read() + '\n\n' + sub(r':func:`([a-zA-Z0-9_]+)`', r'\1', '\n'.join(open('docs/versions.rst').read() .splitlines()[1:]) .replace('.. automodule:: more_itertools', '')), author='Erik Rose', author_email='erikrose@grinchcentral.com', license='MIT', packages=find_packages(exclude=['ez_setup']), install_requires=['six>=1.0.0,<2.0.0'], tests_require=['nose'], test_suite='nose.collector', url='https://github.com/erikrose/more-itertools', include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries'], keywords=['itertools', 'iterator', 'iteration', 'filter', 'peek', 'peekable', 'collate', 'chunk', 'chunked'], ) more-itertools-3.2.0/docs/0000775000175000017500000000000013117757613014467 5ustar bobo00000000000000more-itertools-3.2.0/docs/versions.rst0000664000175000017500000001143513117606150017062 0ustar bobo00000000000000=============== Version History =============== .. automodule:: more_itertools 3.2.0 ----- * New itertools: * :func:`lstrip`, :func:`rstrip`, and :func:`strip` (thanks to MSeifert04 and pylang) * :func:`islice_extended` * Improvements to existing itertools: * Some bugs with slicing :func:`peekable`-wrapped iterables were fixed 3.1.0 ----- * New itertools: * :func:`numeric_range` (Thanks to BebeSparkelSparkel and MSeifert04) * :func:`count_cycle` (Thanks to BebeSparkelSparkel) * :func:`locate` (Thanks to pylang and MSeifert04) * Improvements to existing itertools: * A few itertools are now slightly faster due to some function optimizations. (Thanks to MSeifert04) * The docs have been substantially revised with installation notes, categories for library functions, links, and more. (Thanks to pylang) 3.0.0 ----- * Removed itertools: * ``context`` has been removed due to a design flaw - see below for replacement options. (thanks to NeilGirdhar) * Improvements to existing itertools: * ``side_effect`` now supports ``before`` and ``after`` keyword arguments. (Thanks to yardsale8) * PyPy and PyPy3 are now supported. The major version change is due to the removal of the ``context`` function. Replace it with standard ``with`` statement context management: .. code-block:: python # Don't use context() anymore file_obj = StringIO() consume(print(x, file=f) for f in context(file_obj) for x in u'123') # Use a with statement instead file_obj = StringIO() with file_obj as f: consume(print(x, file=f) for x in u'123') 2.6.0 ----- * New itertools: * ``adjacent`` and ``groupby_transform`` (Thanks to diazona) * ``always_iterable`` (Thanks to jaraco) * (Removed in 3.0.0) ``context`` (Thanks to yardsale8) * ``divide`` (Thanks to mozbhearsum) * Improvements to existing itertools: * ``ilen`` is now slightly faster. (Thanks to wbolster) * ``peekable`` can now prepend items to an iterable. (Thanks to diazona) 2.5.0 ----- * New itertools: * ``distribute`` (Thanks to mozbhearsum and coady) * ``sort_together`` (Thanks to clintval) * ``stagger`` and ``zip_offset`` (Thanks to joshbode) * ``padded`` * Improvements to existing itertools: * ``peekable`` now handles negative indexes and slices with negative components properly. * ``intersperse`` is now slightly faster. (Thanks to pylang) * ``windowed`` now accepts a ``step`` keyword argument. (Thanks to pylang) * Python 3.6 is now supported. 2.4.1 ----- * Move docs 100% to readthedocs.io. 2.4 ----- * New itertools: * ``accumulate``, ``all_equal``, ``first_true``, ``partition``, and ``tail`` from the itertools documentation. * ``bucket`` (Thanks to Rosuav and cvrebert) * ``collapse`` (Thanks to abarnet) * ``interleave`` and ``interleave_longest`` (Thanks to abarnet) * ``side_effect`` (Thanks to nvie) * ``sliced`` (Thanks to j4mie and coady) * ``split_before`` and ``split_after`` (Thanks to astronouth7303) * ``spy`` (Thanks to themiurgo and mathieulongtin) * Improvements to existing itertools: * ``chunked`` is now simpler and more friendly to garbage collection. (Contributed by coady, with thanks to piskvorky) * ``collate`` now delegates to ``heapq.merge`` when possible. (Thanks to kmike and julianpistorius) * ``peekable``-wrapped iterables are now indexable and sliceable. Iterating through ``peekable``-wrapped iterables is also faster. * ``one`` and ``unique_to_each`` have been simplified. (Thanks to coady) 2.3 ----- * Added ``one`` from ``jaraco.util.itertools``. (Thanks, jaraco!) * Added ``distinct_permutations`` and ``unique_to_each``. (Contributed by bbayles) * Added ``windowed``. (Contributed by bbayles, with thanks to buchanae, jaraco, and abarnert) * Simplified the implementation of ``chunked``. (Thanks, nvie!) * Python 3.5 is now supported. Python 2.6 is no longer supported. * Python 3 is now supported directly; there is no 2to3 step. 2.2 ----- * Added ``iterate`` and ``with_iter``. (Thanks, abarnert!) 2.1 ----- * Added (tested!) implementations of the recipes from the itertools documentation. (Thanks, Chris Lonnen!) * Added ``ilen``. (Thanks for the inspiration, Matt Basta!) 2.0 ----- * ``chunked`` now returns lists rather than tuples. After all, they're homogeneous. This slightly backward-incompatible change is the reason for the major version bump. * Added ``@consumer``. * Improved test machinery. 1.1 ----- * Added ``first`` function. * Added Python 3 support. * Added a default arg to ``peekable.peek()``. * Noted how to easily test whether a peekable iterator is exhausted. * Rewrote documentation. 1.0 ----- * Initial release, with ``collate``, ``peekable``, and ``chunked``. Could really use better docs. more-itertools-3.2.0/docs/index.rst0000664000175000017500000000023313105612272016312 0ustar bobo00000000000000.. include:: ../README.rst Contents ======== .. toctree:: :maxdepth: 2 api .. toctree:: :maxdepth: 1 license testing versions more-itertools-3.2.0/docs/conf.py0000664000175000017500000001733213117606211015757 0ustar bobo00000000000000# -*- coding: utf-8 -*- # # more-itertools documentation build configuration file, created by # sphinx-quickstart on Mon Jun 25 20:42:39 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'more-itertools' copyright = u'2012, Erik Rose' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.2.0' # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'more-itertoolsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'more-itertools.tex', u'more-itertools Documentation', u'Erik Rose', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'more-itertools', u'more-itertools Documentation', [u'Erik Rose'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'more-itertools', u'more-itertools Documentation', u'Erik Rose', 'more-itertools', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' more-itertools-3.2.0/docs/api.rst0000664000175000017500000000646613117605216015775 0ustar bobo00000000000000============= API Reference ============= .. automodule:: more_itertools Grouping ======== These tools yield groups of items from a source iterable. ---- **New itertools** .. autofunction:: chunked .. autofunction:: sliced .. autofunction:: distribute .. autofunction:: divide .. autofunction:: split_before .. autofunction:: split_after .. autofunction:: bucket ---- **Itertools recipes** .. autofunction:: grouper .. autofunction:: partition Lookahead ========= These tools peek at an iterable's values without advancing it. ---- **New itertools** .. autofunction:: spy .. autoclass:: peekable Windowing ========= These tools yield windows of items from an iterable. ---- **New itertools** .. autofunction:: windowed .. autofunction:: stagger ---- **Itertools recipes** .. autofunction:: pairwise Augmenting ========== These tools yield items from an iterable, plus additional data. ---- **New itertools** .. autofunction:: count_cycle .. autofunction:: intersperse .. autofunction:: padded .. autofunction:: adjacent .. autofunction:: groupby_transform ---- **Itertools recipes** .. autofunction:: padnone .. autofunction:: ncycles Combining ========= These tools combine multiple iterables. ---- **New itertools** .. autofunction:: collapse .. autofunction:: sort_together .. autofunction:: interleave .. autofunction:: interleave_longest .. autofunction:: collate(*iterables, key=lambda a: a, reverse=False) .. autofunction:: zip_offset(*iterables, offsets, longest=False, fillvalue=None) ---- **Itertools recipes** .. autofunction:: dotproduct .. autofunction:: flatten .. autofunction:: roundrobin Summarizing =========== These tools return summarized or aggregated data from an iterable. ---- **New itertools** .. autofunction:: ilen .. autofunction:: first(iterable[, default]) .. autofunction:: one .. autofunction:: unique_to_each .. autofunction:: locate ---- **Itertools recipes** .. autofunction:: all_equal .. autofunction:: first_true .. autofunction:: nth .. autofunction:: quantify Selecting ========= These yools yield certain items from an iterable. ---- **New itertools** .. autofunction:: islice_extended(start, stop, step) .. autofunction:: strip .. autofunction:: lstrip .. autofunction:: rstrip ---- **Itertools recipes** .. autofunction:: take .. autofunction:: tail .. autofunction:: unique_everseen .. autofunction:: unique_justseen Combinatorics ============= These tools yield combinatorial arrangements of items from iterables. ---- **New itertools** .. autofunction:: distinct_permutations ---- **Itertools recipes** .. autofunction:: powerset .. autofunction:: random_product .. autofunction:: random_permutation .. autofunction:: random_combination .. autofunction:: random_combination_with_replacement Wrapping ======== These tools provide wrappers to smooth working with objects that produce or consume iterables. ---- **New itertools** .. autofunction:: always_iterable .. autofunction:: consumer .. autofunction:: with_iter ---- **Itertools recipes** .. autofunction:: iter_except Others ====== **New itertools** .. autofunction:: numeric_range(start, stop, step) .. autofunction:: side_effect .. autofunction:: iterate ---- **Itertools recipes** .. autofunction:: consume .. autofunction:: accumulate .. autofunction:: tabulate .. autofunction:: repeatfunc more-itertools-3.2.0/docs/make.bat0000664000175000017500000001177013006760013016063 0ustar bobo00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\more-itertools.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\more-itertools.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end more-itertools-3.2.0/docs/Makefile0000664000175000017500000001273413006760013016117 0ustar bobo00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/more-itertools.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/more-itertools.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/more-itertools" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/more-itertools" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." more-itertools-3.2.0/docs/testing.rst0000664000175000017500000000055413006760013016663 0ustar bobo00000000000000======= Testing ======= more-itertools uses nose for its tests. First, install nose:: pip install nose Then, run the tests like this:: nosetests --with-doctest Multiple Python Versions ======================== To run the tests on all the versions of Python more-itertools supports, install tox:: pip install tox Then, run the tests:: tox more-itertools-3.2.0/docs/license.rst0000664000175000017500000000120613034170747016635 0ustar bobo00000000000000======= License ======= more-itertools is under the MIT License. See the LICENSE file. Conditions for Contributors =========================== By contributing to this software project, you are agreeing to the following terms and conditions for your contributions: First, you agree your contributions are submitted under the MIT license. Second, you represent you are authorized to make the contributions and grant the license. If your employer has rights to intellectual property that includes your contributions, you represent that you have received permission to make contributions and grant the required license on behalf of that employer. more-itertools-3.2.0/tox.ini0000664000175000017500000000030213050474636015042 0ustar bobo00000000000000[tox] envlist = py27, py32, py33, py34, py35 [tox:travis] 2.7 = py27 3.3 = py33 3.4 = py34 3.5 = py35 [testenv] commands = nosetests more_itertools --with-doctest deps = nose changedir = .tox more-itertools-3.2.0/README.rst0000664000175000017500000000352113105612272015213 0ustar bobo00000000000000============== More Itertools ============== .. image:: https://coveralls.io/repos/github/erikrose/more-itertools/badge.svg?branch=master :target: https://coveralls.io/github/erikrose/more-itertools?branch=master Python's ``itertools`` library is a gem - you can compose elegant solutions for a variety of problems with the functions it provides. In ``more-itertools`` we collect additional building blocks, recipes, and routines for working with Python iterables. Getting started =============== To get started, install the library with `pip `_: .. code-block:: shell pip install more-itertools The recipes from the `itertools docs `_ are included in the top-level package: .. code-block:: python >>> from more_itertools import flatten >>> iterable = [(0, 1), (2, 3)] >>> list(flatten(iterable)) [0, 1, 2, 3] Several new recipes are available as well: .. code-block:: python >>> from more_itertools import chunked >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> list(chunked(iterable, 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> from more_itertools import spy >>> iterable = (x * x for x in range(1, 6)) >>> head, iterable = spy(iterable, n=3) >>> list(head) [1, 4, 9] >>> list(iterable) [1, 4, 9, 16, 25] For the full listing of functions, see the `API documentation `_. Development =========== ``more-itertools`` is maintained by `@erikrose `_ and `@bbayles `_, with help from `many others `_. If you have a problem or suggestion, please file a bug or pull request in this repository. Thanks for contributing! more-itertools-3.2.0/more_itertools.egg-info/0000775000175000017500000000000013117757613020277 5ustar bobo00000000000000more-itertools-3.2.0/more_itertools.egg-info/SOURCES.txt0000664000175000017500000000103113117757613022156 0ustar bobo00000000000000LICENSE MANIFEST.in README.rst setup.py tox.ini docs/Makefile docs/api.rst docs/conf.py docs/index.rst docs/license.rst docs/make.bat docs/testing.rst docs/versions.rst more_itertools/__init__.py more_itertools/more.py more_itertools/recipes.py more_itertools.egg-info/PKG-INFO more_itertools.egg-info/SOURCES.txt more_itertools.egg-info/dependency_links.txt more_itertools.egg-info/requires.txt more_itertools.egg-info/top_level.txt more_itertools/tests/__init__.py more_itertools/tests/test_more.py more_itertools/tests/test_recipes.pymore-itertools-3.2.0/more_itertools.egg-info/requires.txt0000664000175000017500000000002213117757613022671 0ustar bobo00000000000000six>=1.0.0,<2.0.0 more-itertools-3.2.0/more_itertools.egg-info/top_level.txt0000664000175000017500000000001713117757613023027 0ustar bobo00000000000000more_itertools more-itertools-3.2.0/more_itertools.egg-info/dependency_links.txt0000664000175000017500000000000113117757613024345 0ustar bobo00000000000000 more-itertools-3.2.0/more_itertools.egg-info/PKG-INFO0000664000175000017500000002220713117757613021377 0ustar bobo00000000000000Metadata-Version: 1.1 Name: more-itertools Version: 3.2.0 Summary: More routines for operating on iterables, beyond itertools Home-page: https://github.com/erikrose/more-itertools Author: Erik Rose Author-email: erikrose@grinchcentral.com License: MIT Description: ============== More Itertools ============== .. image:: https://coveralls.io/repos/github/erikrose/more-itertools/badge.svg?branch=master :target: https://coveralls.io/github/erikrose/more-itertools?branch=master Python's ``itertools`` library is a gem - you can compose elegant solutions for a variety of problems with the functions it provides. In ``more-itertools`` we collect additional building blocks, recipes, and routines for working with Python iterables. Getting started =============== To get started, install the library with `pip `_: .. code-block:: shell pip install more-itertools The recipes from the `itertools docs `_ are included in the top-level package: .. code-block:: python >>> from more_itertools import flatten >>> iterable = [(0, 1), (2, 3)] >>> list(flatten(iterable)) [0, 1, 2, 3] Several new recipes are available as well: .. code-block:: python >>> from more_itertools import chunked >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> list(chunked(iterable, 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> from more_itertools import spy >>> iterable = (x * x for x in range(1, 6)) >>> head, iterable = spy(iterable, n=3) >>> list(head) [1, 4, 9] >>> list(iterable) [1, 4, 9, 16, 25] For the full listing of functions, see the `API documentation `_. Development =========== ``more-itertools`` is maintained by `@erikrose `_ and `@bbayles `_, with help from `many others `_. If you have a problem or suggestion, please file a bug or pull request in this repository. Thanks for contributing! Version History =============== 3.2.0 ----- * New itertools: * lstrip, rstrip, and strip (thanks to MSeifert04 and pylang) * islice_extended * Improvements to existing itertools: * Some bugs with slicing peekable-wrapped iterables were fixed 3.1.0 ----- * New itertools: * numeric_range (Thanks to BebeSparkelSparkel and MSeifert04) * count_cycle (Thanks to BebeSparkelSparkel) * locate (Thanks to pylang and MSeifert04) * Improvements to existing itertools: * A few itertools are now slightly faster due to some function optimizations. (Thanks to MSeifert04) * The docs have been substantially revised with installation notes, categories for library functions, links, and more. (Thanks to pylang) 3.0.0 ----- * Removed itertools: * ``context`` has been removed due to a design flaw - see below for replacement options. (thanks to NeilGirdhar) * Improvements to existing itertools: * ``side_effect`` now supports ``before`` and ``after`` keyword arguments. (Thanks to yardsale8) * PyPy and PyPy3 are now supported. The major version change is due to the removal of the ``context`` function. Replace it with standard ``with`` statement context management: .. code-block:: python # Don't use context() anymore file_obj = StringIO() consume(print(x, file=f) for f in context(file_obj) for x in u'123') # Use a with statement instead file_obj = StringIO() with file_obj as f: consume(print(x, file=f) for x in u'123') 2.6.0 ----- * New itertools: * ``adjacent`` and ``groupby_transform`` (Thanks to diazona) * ``always_iterable`` (Thanks to jaraco) * (Removed in 3.0.0) ``context`` (Thanks to yardsale8) * ``divide`` (Thanks to mozbhearsum) * Improvements to existing itertools: * ``ilen`` is now slightly faster. (Thanks to wbolster) * ``peekable`` can now prepend items to an iterable. (Thanks to diazona) 2.5.0 ----- * New itertools: * ``distribute`` (Thanks to mozbhearsum and coady) * ``sort_together`` (Thanks to clintval) * ``stagger`` and ``zip_offset`` (Thanks to joshbode) * ``padded`` * Improvements to existing itertools: * ``peekable`` now handles negative indexes and slices with negative components properly. * ``intersperse`` is now slightly faster. (Thanks to pylang) * ``windowed`` now accepts a ``step`` keyword argument. (Thanks to pylang) * Python 3.6 is now supported. 2.4.1 ----- * Move docs 100% to readthedocs.io. 2.4 ----- * New itertools: * ``accumulate``, ``all_equal``, ``first_true``, ``partition``, and ``tail`` from the itertools documentation. * ``bucket`` (Thanks to Rosuav and cvrebert) * ``collapse`` (Thanks to abarnet) * ``interleave`` and ``interleave_longest`` (Thanks to abarnet) * ``side_effect`` (Thanks to nvie) * ``sliced`` (Thanks to j4mie and coady) * ``split_before`` and ``split_after`` (Thanks to astronouth7303) * ``spy`` (Thanks to themiurgo and mathieulongtin) * Improvements to existing itertools: * ``chunked`` is now simpler and more friendly to garbage collection. (Contributed by coady, with thanks to piskvorky) * ``collate`` now delegates to ``heapq.merge`` when possible. (Thanks to kmike and julianpistorius) * ``peekable``-wrapped iterables are now indexable and sliceable. Iterating through ``peekable``-wrapped iterables is also faster. * ``one`` and ``unique_to_each`` have been simplified. (Thanks to coady) 2.3 ----- * Added ``one`` from ``jaraco.util.itertools``. (Thanks, jaraco!) * Added ``distinct_permutations`` and ``unique_to_each``. (Contributed by bbayles) * Added ``windowed``. (Contributed by bbayles, with thanks to buchanae, jaraco, and abarnert) * Simplified the implementation of ``chunked``. (Thanks, nvie!) * Python 3.5 is now supported. Python 2.6 is no longer supported. * Python 3 is now supported directly; there is no 2to3 step. 2.2 ----- * Added ``iterate`` and ``with_iter``. (Thanks, abarnert!) 2.1 ----- * Added (tested!) implementations of the recipes from the itertools documentation. (Thanks, Chris Lonnen!) * Added ``ilen``. (Thanks for the inspiration, Matt Basta!) 2.0 ----- * ``chunked`` now returns lists rather than tuples. After all, they're homogeneous. This slightly backward-incompatible change is the reason for the major version bump. * Added ``@consumer``. * Improved test machinery. 1.1 ----- * Added ``first`` function. * Added Python 3 support. * Added a default arg to ``peekable.peek()``. * Noted how to easily test whether a peekable iterator is exhausted. * Rewrote documentation. 1.0 ----- * Initial release, with ``collate``, ``peekable``, and ``chunked``. Could really use better docs. Keywords: itertools,iterator,iteration,filter,peek,peekable,collate,chunk,chunked Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Natural Language :: English Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Software Development :: Libraries more-itertools-3.2.0/LICENSE0000664000175000017500000000203513006760013014525 0ustar bobo00000000000000Copyright (c) 2012 Erik Rose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. more-itertools-3.2.0/setup.cfg0000664000175000017500000000004613117757613015360 0ustar bobo00000000000000[egg_info] tag_build = tag_date = 0 more-itertools-3.2.0/PKG-INFO0000664000175000017500000002220713117757613014637 0ustar bobo00000000000000Metadata-Version: 1.1 Name: more-itertools Version: 3.2.0 Summary: More routines for operating on iterables, beyond itertools Home-page: https://github.com/erikrose/more-itertools Author: Erik Rose Author-email: erikrose@grinchcentral.com License: MIT Description: ============== More Itertools ============== .. image:: https://coveralls.io/repos/github/erikrose/more-itertools/badge.svg?branch=master :target: https://coveralls.io/github/erikrose/more-itertools?branch=master Python's ``itertools`` library is a gem - you can compose elegant solutions for a variety of problems with the functions it provides. In ``more-itertools`` we collect additional building blocks, recipes, and routines for working with Python iterables. Getting started =============== To get started, install the library with `pip `_: .. code-block:: shell pip install more-itertools The recipes from the `itertools docs `_ are included in the top-level package: .. code-block:: python >>> from more_itertools import flatten >>> iterable = [(0, 1), (2, 3)] >>> list(flatten(iterable)) [0, 1, 2, 3] Several new recipes are available as well: .. code-block:: python >>> from more_itertools import chunked >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> list(chunked(iterable, 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> from more_itertools import spy >>> iterable = (x * x for x in range(1, 6)) >>> head, iterable = spy(iterable, n=3) >>> list(head) [1, 4, 9] >>> list(iterable) [1, 4, 9, 16, 25] For the full listing of functions, see the `API documentation `_. Development =========== ``more-itertools`` is maintained by `@erikrose `_ and `@bbayles `_, with help from `many others `_. If you have a problem or suggestion, please file a bug or pull request in this repository. Thanks for contributing! Version History =============== 3.2.0 ----- * New itertools: * lstrip, rstrip, and strip (thanks to MSeifert04 and pylang) * islice_extended * Improvements to existing itertools: * Some bugs with slicing peekable-wrapped iterables were fixed 3.1.0 ----- * New itertools: * numeric_range (Thanks to BebeSparkelSparkel and MSeifert04) * count_cycle (Thanks to BebeSparkelSparkel) * locate (Thanks to pylang and MSeifert04) * Improvements to existing itertools: * A few itertools are now slightly faster due to some function optimizations. (Thanks to MSeifert04) * The docs have been substantially revised with installation notes, categories for library functions, links, and more. (Thanks to pylang) 3.0.0 ----- * Removed itertools: * ``context`` has been removed due to a design flaw - see below for replacement options. (thanks to NeilGirdhar) * Improvements to existing itertools: * ``side_effect`` now supports ``before`` and ``after`` keyword arguments. (Thanks to yardsale8) * PyPy and PyPy3 are now supported. The major version change is due to the removal of the ``context`` function. Replace it with standard ``with`` statement context management: .. code-block:: python # Don't use context() anymore file_obj = StringIO() consume(print(x, file=f) for f in context(file_obj) for x in u'123') # Use a with statement instead file_obj = StringIO() with file_obj as f: consume(print(x, file=f) for x in u'123') 2.6.0 ----- * New itertools: * ``adjacent`` and ``groupby_transform`` (Thanks to diazona) * ``always_iterable`` (Thanks to jaraco) * (Removed in 3.0.0) ``context`` (Thanks to yardsale8) * ``divide`` (Thanks to mozbhearsum) * Improvements to existing itertools: * ``ilen`` is now slightly faster. (Thanks to wbolster) * ``peekable`` can now prepend items to an iterable. (Thanks to diazona) 2.5.0 ----- * New itertools: * ``distribute`` (Thanks to mozbhearsum and coady) * ``sort_together`` (Thanks to clintval) * ``stagger`` and ``zip_offset`` (Thanks to joshbode) * ``padded`` * Improvements to existing itertools: * ``peekable`` now handles negative indexes and slices with negative components properly. * ``intersperse`` is now slightly faster. (Thanks to pylang) * ``windowed`` now accepts a ``step`` keyword argument. (Thanks to pylang) * Python 3.6 is now supported. 2.4.1 ----- * Move docs 100% to readthedocs.io. 2.4 ----- * New itertools: * ``accumulate``, ``all_equal``, ``first_true``, ``partition``, and ``tail`` from the itertools documentation. * ``bucket`` (Thanks to Rosuav and cvrebert) * ``collapse`` (Thanks to abarnet) * ``interleave`` and ``interleave_longest`` (Thanks to abarnet) * ``side_effect`` (Thanks to nvie) * ``sliced`` (Thanks to j4mie and coady) * ``split_before`` and ``split_after`` (Thanks to astronouth7303) * ``spy`` (Thanks to themiurgo and mathieulongtin) * Improvements to existing itertools: * ``chunked`` is now simpler and more friendly to garbage collection. (Contributed by coady, with thanks to piskvorky) * ``collate`` now delegates to ``heapq.merge`` when possible. (Thanks to kmike and julianpistorius) * ``peekable``-wrapped iterables are now indexable and sliceable. Iterating through ``peekable``-wrapped iterables is also faster. * ``one`` and ``unique_to_each`` have been simplified. (Thanks to coady) 2.3 ----- * Added ``one`` from ``jaraco.util.itertools``. (Thanks, jaraco!) * Added ``distinct_permutations`` and ``unique_to_each``. (Contributed by bbayles) * Added ``windowed``. (Contributed by bbayles, with thanks to buchanae, jaraco, and abarnert) * Simplified the implementation of ``chunked``. (Thanks, nvie!) * Python 3.5 is now supported. Python 2.6 is no longer supported. * Python 3 is now supported directly; there is no 2to3 step. 2.2 ----- * Added ``iterate`` and ``with_iter``. (Thanks, abarnert!) 2.1 ----- * Added (tested!) implementations of the recipes from the itertools documentation. (Thanks, Chris Lonnen!) * Added ``ilen``. (Thanks for the inspiration, Matt Basta!) 2.0 ----- * ``chunked`` now returns lists rather than tuples. After all, they're homogeneous. This slightly backward-incompatible change is the reason for the major version bump. * Added ``@consumer``. * Improved test machinery. 1.1 ----- * Added ``first`` function. * Added Python 3 support. * Added a default arg to ``peekable.peek()``. * Noted how to easily test whether a peekable iterator is exhausted. * Rewrote documentation. 1.0 ----- * Initial release, with ``collate``, ``peekable``, and ``chunked``. Could really use better docs. Keywords: itertools,iterator,iteration,filter,peek,peekable,collate,chunk,chunked Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Natural Language :: English Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Software Development :: Libraries more-itertools-3.2.0/MANIFEST.in0000664000175000017500000000023213007426610015256 0ustar bobo00000000000000include README.rst include LICENSE include docs/*.rst include docs/Makefile include docs/make.bat include docs/conf.py include fabfile.py include tox.ini