I wish to establish if a continuous sequence exists within a tuple.
For example, I wish to return True
in this case:
is_sequence_within((1,2), (1,2,3))
and False
in this case:
is_sequence_within((1,3), (1,2,3))
I wish to establish if a continuous sequence exists within a tuple.
For example, I wish to return True
in this case:
is_sequence_within((1,2), (1,2,3))
and False
in this case:
is_sequence_within((1,3), (1,2,3))
I feel like this is something that itertools
will handle more elegantly, but....
def is_sequence_within(seq, target):
for i in range(len(target)-len(seq)+1):
if seq == target[i:i+len(seq)]: return True
return False
Alternatively:
def is_sequence_within(seq, target):
return any(seq==target[i:i+len(seq)] for i in range(len(target)+1-len(seq)))
You can try the following:
def is_subset(key, tup):
for i in range(len(tup) - len(key) + 1):
if key == tup[i : i + l]:
return True
return False
Or in a shorter way:
def is_subset(key, tup):
return any(key == tup[i:i + len(key)] for i in range(len(tup) - len(key) + 1))
Output:
print is_subset((1, 2), (1, 2, 3)) # True
print is_subset((1, 3), (1, 2, 3)) # False
A simple trick would be to rely on substring search (that is quite optimized in Python)
def is_sequence_within(needle, haystack):
if len(needle) == 0:
return True
return ("," + ",".join(map(str, needle)) + "," in
"," + ",".join(map(str, haystack)) + ",")
if this is doable and/or efficient or not depends on how big are the tuples and what is the content.
Of course if you also search the same sequence for many subsequences then caching the haystack string would be much better.