Test if list contains another list

Derek Martin code at pizzashack.org
Fri Sep 26 21:25:08 CEST 2008


On Thu, Sep 18, 2008 at 03:24:16AM -0700, gauravatnet at gmail.com wrote:
> I looked inside this thread for my query which brought me the
> following google search result
> "Test if list contains another list - comp.lang.python | Google
> Groups"
> 
> But then I was disappointed to see the question asked was not exactly
> right. 
[...]
> def findAllMatchingList(mainList, subList):
>     resultIndex = []
>     globalIndex = 0
>     for i in range(len(mainList)):
>         if i < globalIndex:
>             continue
>         globalIndex = i
>         increment = 0
>         for j in range(len(subList)):
>             if mainList[globalIndex] == subList[j]:
>                 globalIndex += 1
>                 increment += 1
>                 if j == (len(subList)-1):
>                     resultIndex.append(globalIndex-increment)
>             else:
>                 break
> 
>     return resultIndex

I didn't time them to compare, but how about this instead:

>>> def find_needle_in_haystack(needle, haystack):                                                         
...     r = []
...     L = len(needle)
...     for i in range(len(haystack)):
...             if haystack[i:i+L] == needle:
...                     r.append(i)
...     return r

>>> # this fails because "3" is not 3...                                                                   
>>> find_needle_in_haystack([1,2,3], ["a","b",1,2,"3","9"])                                                
[]
>>> find_needle_in_haystack([1,2,3], [1,2,3])                                                              
[0]
>>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9"])                                                  
[2]
>>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9","q",1,2,3])                                        
[2, 7]

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/48921ad9/attachment.pgp>


More information about the Python-list mailing list