# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""A useful generator: groupby().

This may end up in the Python standard library for Python 2.4.

Also here: findruns(), which is similar but looks for runs of
consecutive integer keys.

"""

def groupby(seq, key=lambda x: x):
    """Helper to divide a sequence up in groups."""
    it = iter(seq)
    try:
        value = next(it)
    except StopIteration:
        return
    oldkey = key(value)
    group = [value]
    for value in it:
        newkey = key(value)
        if newkey == oldkey:
            group.append(value)
        else:
            yield oldkey, group
            group = [value]
            oldkey = newkey
    yield oldkey, group

# Something similar to find runs of consecutive values

def findruns(seq, key=lambda x: x):
    """Helper to find runs of consecutive key values."""
    it = iter(seq)
    try:
        value = next(it)
    except StopIteration:
        return
    firstkey = lastkey = key(value)
    group = [value]
    for value in it:
        newkey = key(value)
        if newkey == lastkey+1:
            lastkey = newkey
            group.append(value)
        else:
            yield firstkey, lastkey, group
            group = [value]
            firstkey = lastkey = newkey
    yield firstkey, lastkey, group

