"""Iterator and generator snippets (lazy, memory friendly)."""
from itertools import chain, count, groupby, islice, tee


def take(iterable, n):
    """First ``n`` items of any iterable as a list.

    >>> take(count(10), 3)
    [10, 11, 12]
    """
    return list(islice(iterable, n))


def batched(iterable, n):
    """Yield tuples of up to ``n`` items (itertools.batched exists in 3.12+).

    >>> list(batched('ABCDEFG', 3))
    [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
    """
    if n < 1:
        raise ValueError('n must be >= 1')
    it = iter(iterable)
    while chunk := tuple(islice(it, n)):
        yield chunk


def pairwise(iterable):
    """Consecutive overlapping pairs (itertools.pairwise exists in 3.10+).

    >>> list(pairwise([1, 2, 3, 4]))
    [(1, 2), (2, 3), (3, 4)]
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


def interleave(*iterables):
    """Round-robin items from several iterables until all are exhausted.

    >>> list(interleave('AB', '1234', 'x'))
    ['A', '1', 'x', 'B', '2', '3', '4']
    """
    iterators = [iter(it) for it in iterables]
    while iterators:
        alive = []
        for it in iterators:
            try:
                yield next(it)
                alive.append(it)
            except StopIteration:
                pass
        iterators = alive


def run_length(iterable):
    """Run-length encode: (value, count) for each run of equal values.

    >>> run_length('aaabccdddd')
    [('a', 3), ('b', 1), ('c', 2), ('d', 4)]
    """
    return [(k, sum(1 for _ in g)) for k, g in groupby(iterable)]


def flatten_iter(iterables):
    """Lazily chain an iterable of iterables.

    >>> list(flatten_iter([range(2), 'ab', (9,)]))
    [0, 1, 'a', 'b', 9]
    """
    return chain.from_iterable(iterables)


def nth(iterable, n, default=None):
    """The item at index ``n`` of any iterable, or ``default``.

    >>> nth((x * x for x in range(10)), 4), nth([], 2, 'missing')
    (16, 'missing')
    """
    return next(islice(iterable, n, None), default)


def ilen(iterable):
    """Count items of an iterator without building a list.

    >>> ilen(x for x in range(1000) if x % 7 == 0)
    143
    """
    return sum(1 for _ in iterable)


def peek(iterable):
    """Look at the first item and get back an iterator that still includes it.

    >>> head, it = peek(iter([1, 2, 3]))
    >>> head, list(it)
    (1, [1, 2, 3])
    """
    it = iter(iterable)
    try:
        head = next(it)
    except StopIteration:
        return None, iter(())
    return head, chain([head], it)
