are elements of a list in sequence in list b
Tomek Paczkowski
oinopion at gmail.com
Fri Feb 8 16:58:17 EST 2008
Matthew_WARREN at bnpparibas.com wrote:
> Hallo,
>
>
> I need to search list a for the sequence of list b
>
I guess most pythonic would be sth like this:
[code]
def naive_seq_match(sequence, pattern):
"""Serches for pattern in sequence. If pattern is found
returns match start index, else returns None"""
plen = len(pattern)
for ind in xrange(len(sequence) - plen + 1):
if sequence[ind:ind+plen] == pattern:
return ind
return None
[/code]
It can be used with every sequence, not only lists. If its not fast enough
(its pessimistic complexity is O(n^2)), you can try Knuth-Morris-Pratt
algorithm (its O(n), but requires some precomputation).
--
Oinopion
http://www.hauru.eu
More information about the Python-list
mailing list