On Aug 16, 8:23 am, Alain Ketterlin <al...@dpt-info.u-strasbg.fr> wrote: > Roy Smith <r...@panix.com> writes: > >> what is the best way to check if a given list (lets call it l1) is > >> totally contained in a second list (l2)? > > [...] > > > import re > > > def sublist(l1, l2): > > s1 = ''.join(map(str, l1)) > > s2 = ''.join(map(str, l2)) > > return re.search(s1, s2) > > This is complete nonsense (try it on [12] and [1,2]). > > The original problem is "string searching" (where strings here are > sequences of numbers instead of characters). See > > http://en.wikipedia.org/wiki/String_searching_algorithm > > for any algorithm (Rabin-Karp seems appropriate to me). > > -- Alain.
That can be easily fixed: >>> def sublist(lst1, lst2): s1 = ','.join(map(str, lst1)) s2 = ','.join(map(str, lst2)) return False if s2.find(s1)==-1 else True >>> sublist([1,2],[1,2,3,4,5]) True >>> sublist([1,2,2],[1,2,3,4,5]) False >>> sublist([1,2,3],[1,3,5,7]) False >>> sublist([12],[1,2]) False >>> I don't know about best, but it works for the examples given. -- http://mail.python.org/mailman/listinfo/python-list