# AUTOGENERATED! DO NOT EDIT! File to edit: 15_core_spells.ipynb (unless otherwise specified).

__all__ = ['get_spells', 'get_longest_spell', 'get_spell_durations']

# Cell
def get_spells(sequence):
    "Returns a list of tuples where each tuple holds the element and the length of the spell (also known as run or episode) for each spell in the sequence."

    # get each spell and its length
    spells = [(k, sum(1 for x in v)) for k,v in itertools.groupby(sequence)]
    # this is functionally equivalent to the following;
    # spells = [(k, len(list(v))) for k,v in itertools.groupby(sequence)]

    return spells

# Cell
def get_longest_spell(sequence):
    "Returns a dict containing the element, count, and starting position of the longest spell in the sequence. The keys of this dict are 'element, 'count', and 'start'."

    spells = get_spells(sequence)

    longest_spell = max(count for element, count in spells)

    for i, (element, count) in enumerate(spells):
        if count == longest_spell:
            # sum the counts of all previous spells to get its starting position
            position_in_sequence = sum(count for _,count in spells[:i])

            return {'element':element, 'count':count,'start':position_in_sequence}

# Cell
def get_spell_durations(sequence):
    "Computes the durations of each spell in the sequence, returning a list."

    spells = get_spells(sequence)
    durations = [spell[1] for spell in spells]

    return durations