finding all sublists of list2 that are identical to list1

Diez B. Roggisch nospam-deets at web.de
Mon Feb 9 12:04:37 EST 2004


> def sublist(list1, list2):
>     len1 = len(list1)
>     rnge = xrange(len(list2))
>     return [i for i in rnge if list2[i:len1+i] == list1]

Nice one - looks like I optimized too much. 
 
> If you need this for a specific purpose, you might be able to
> transform the data and try a different technique which would be
> executed internally at the "C" level.  For example, if your list is
> always integers, you might be able to join them into a tab-delimited
> string and scan the string with a regular expression (unless you
> consider that building automata).

You don't gain anything by that - it would still perform the search in
>O(n). But your idea makes sense when the created "strings" would then be
used in a better perforiming string searching algorithm like shift-and.

-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list