testing if a list contains a sublist

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 16 04:19:43 EDT 2011


On Tue, 16 Aug 2011 12:12 pm Steven D'Aprano wrote:

> On Tue, 16 Aug 2011 09:26 am Johannes wrote:
> 
>> hi list,
>> what is the best way to check if a given list (lets call it l1) is
>> totally contained in a second list (l2)?
> 
> This is not the most efficient algorithm, but for short lists it should be
> plenty fast enough:

Nope, sorry, that was buggy. Here's another version which should be accurate
but may be slower.

def search(source, target, start=0, end=None):
    """Naive search for target in source."""
    m = len(source)
    n = len(target)
    if end is None:
        end = m
    if n == 0 or m < n:
        return None
    for i in range(start, end-n+1):
        if source[i:i+n] == target:
            return i
    return None



-- 
Steven




More information about the Python-list mailing list