Reputation: 269
Let's say we have a reference sequence which is a list or tuple:
reference = ['a', 'b', 'c', 'd']
and I want to check if some sequence does exist inside the reference sequence:
target1 = ['a', 'b', 'c'] # true
target2 = ['a', 'c', 'b'] # false
target3 = ['a', 'c', 'd'] # false
target4 = ['c', 'd', 'e'] # false
target5 = ['c', 'd'] # true
Is there any built-in function to check this kind of sequence membership? Thank you!
Upvotes: 0
Views: 408
Reputation: 269
I found a relevant module difflib.SequenceMatcher
.
def sequence_membership(target, reference):
get_eq = lambda x: [c for c in x if c[0]=='equal']
get_length = lambda x: x[2]-x[1]
s = SequenceMatcher(None, target, reference)
match_result = s.get_opcodes()
overlapped = get_eq(match_result)
if len(overlapped) ==1 and get_length(overlapped[0]) == len(target):
return True
else: return False
>>> sequence_membership(target1,reference)
True
>>> sequence_membership(target2,reference)
False
>>> sequence_membership(target3,reference)
False
>>> sequence_membership(target4,reference)
False
>>> sequence_membership(target5,reference)
True
Upvotes: 1
Reputation: 4809
On the first thought, you can convert the list or tuple to string and find if the substring exists in the reference. A simple code snippet to explain my thought:
reference = ['a', 'b', 'c', 'd']
target1 = ['a', 'b', 'c'] # true
list2str = lambda ref: "".join(ref)
base = list2str(reference)
t1 = list2str(target1)
if t1 in base:
print 'found'
else:
print 'unfound'
Upvotes: 0