define 'in' operator on lists
Bengt Richter
bokr at oz.net
Mon Oct 11 07:50:43 EDT 2004
On Mon, 11 Oct 2004 12:51:57 +0200, "..:: sjf ::.." <somebody at unknown.org> wrote:
>pewnego dnia niejaki(a) Duncan Booth wstukal(a) byl(a) co nastepuje...:
>> ..:: sjf ::.. wrote:
>>
>>
>>>I want to define 'in' operator (or any "magic" function) on list which
>>>returns True value if all of list (i.e. _list) elements appears in other
>>>list (i.e. L) in the same order and False otherwise.
>>
>>
>> How about:
>>
>>
>>>>>def containedinsequence(short, long):
>>
>> ilong = iter(long)
>> for s in short:
>> for l in ilong:
>> if s==l:
>> break
>> else:
>> return False # ran out of long list
>> return True
>>
>>
>>>>>L = [1, 2, 3, 4, 5, 6]
>>>>>containedinsequence([3, 4, 6], L)
>>
>
>OK, this is nearly what I am expecting, but I want if
>containedsequence([3, 4, 5], L) returns True, but
>containedsequence([3, 4, 6], L) returns False
>because that sequence not exist in longlist exactly
>
Not very tested (just what you see ;-)
>>> def issubseq(sub,seq):
... if not sub: return True
... sub0 = sub[0]
... start = 0
... lensub = len(sub)
... while True:
... try: start = seq.index(sub0, start)
... except ValueError: return False
... if seq[start:start+lensub] == sub: return True
... start +=1
... return False
...
>>> L = [1, 2, 3, 4, 5, 6]
>>> issubseq([3,4,5],L)
True
>>> issubseq([3,4,6],L)
False
>>> issubseq([3],L)
True
>>> issubseq([],L)
True
>>> issubseq([6],L)
True
>>> issubseq([1,2],L)
True
Regards,
Bengt Richter
More information about the Python-list
mailing list