Identifying the start of good data in a list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Aug 27 17:34:59 EDT 2008


George Sakkis:
> This seems the most efficient so far for arbitrary iterables.

This one probably scores well with Psyco ;-)


def start_good3(seq, good_ones=4):
    """
    >>> start_good = start_good3
    >>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    4
    >>> start_good([])
    -1
    >>> start_good([0, 0])
    -1
    >>> start_good([0, 0, 0])
    -1
    >>> start_good([0, 0, 0, 0, 1])
    -1
    >>> start_good([0, 0, 1, 0, 1, 2, 3])
    -1
    >>> start_good([0, 0, 1, 0, 1, 2, 3, 4])
    4
    >>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5])
    4
    >>> start_good([1, 2, 3, 4])
    0
    >>> start_good([1, 2, 3])
    -1
    >>> start_good([0, 0, 1, 0, 1, 2, 0, 4])
    -1
    """
    n_good = 0
    pos = 0
    for el in seq:
        if el:
            if n_good == good_ones:
                return pos - good_ones
            else:
                n_good += 1
        elif n_good:
                n_good = 0
        pos += 1
    if n_good == good_ones:
        return pos - good_ones
    else:
        return -1

Bye,
bearophile



More information about the Python-list mailing list