Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Neil Cerutti Newsgroups: comp.lang.python Subject: Re: testing if a list contains a sublist Date: 16 Aug 2011 17:45:15 GMT Organization: Norwich University Lines: 74 Message-ID: <9avolbFff6U1@mid.individual.net> References: <8739h18rzj.fsf@dpt-info.u-strasbg.fr> <5e85b065-698e-4cd7-a409-d23618db1c3c@eb1g2000vbb.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Trace: individual.net xviyrDRCW+thzNv3SX+3CAyRwR57uhHdCLf+d2XIyiAhnpD5aq Cancel-Lock: sha1:DkqvCAr3Qc3ryT9MBxFtEZ4eUUo= User-Agent: slrn/0.9.9p1/mm/ao (Win32) Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:11590 On 2011-08-16, nn wrote: > 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,3],[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 >>>> String conversion is risky: >>> sublist(['1,2', '3,4'], [1, 2, 3, 4]) True Since we're bike-shedding, here's my entry. It's not clear to me if accepting iterables rather than lists is a win, but I thought, "Why not be general if the implementation is easy?" def is_subseq_of(x, y): r"""Return True if the elements in iterable x are found contiguously in iterable y. >>> is_subseq_of([], []) True >>> is_subseq_of([], [1, 2, 3]) True >>> is_subseq_of([1], [1, 2, 3]) True >>> is_subseq_of([1], []) False >>> is_subseq_of([4, 5], [1, 2, 3, 4, 5]) True >>> is_subseq_of([1, 2], [1, 3, 2]) False >>> is_subseq_of([2, 3], [1, 2, 3, 4]) True >>> is_subseq_of([1, 2, 2], [1, 2, 3, 4, 5]) False >>> is_subseq_of([1, 2], [1, 2]) True >>> is_subseq_of([1, 2, 3], [1, 2]) False >>> is_subseq_of(['1,2', '3,4'], [1, 2, 3, 4]) False """ x = tuple(x) ix = 0 lenx = len(x) if lenx == 0: return True for elem in y: if x[ix] == elem: ix += 1 else: ix = 0 if ix == lenx: return True return False if __name__ == '__main__': import doctest doctest.testmod() -- Neil Cerutti