testing if a list contains a sublist

Johannes dajo.mail at web.de
Tue Aug 16 17:26:08 CEST 2011


Am 16.08.2011 10:00, schrieb Laszlo Nagy:
> 
>> Error free? Consider this stated requirement:
>>> l1 = [1,2,2,], l2 = [1,2,3,4,5] ->  l1 is not contained in l2
> If you look it the strict way, "containment" relation for lists is meant
> this way:
> 
> 
> l1 = []
> l2 = [1,l1,2]   # l2 CONTAINS l1
> 
> But you are right, I was wrong. So let's clarify what the OP wants!
> 
> For example:
> 
> l1 = [1,2,2,], l2 = [2,1,2,3,4,5]
I dont care about this case, because all list are ordered for me.

I've chosen the following solution

> def _list_contained_in_list(l1,l2):
>     d1 = {}
>     d2 = {}
>     for i in l1:
>         if i in d1:
>             d1[i] += 1
>         else:
>             d1[i] = 1
>     for i in l2:
>         if i in d2:
>             d2[i] += 1
>         else:
>             d2[i] = 1
>     if not all([k in d2.keys() for k in d1.keys()]):
>         return false    
>     return all([d1[i] <= d2[i] for i in d1])


greatz Johannes



More information about the Python-list mailing list