Reputation: 498
For instance, a tuple is (1,0,1,1,1,0) and subtuple is (1,0)
in increasing order, how to find out this subtuple is in the tuple?
Is it only way to compare one by one by using iteration?
Ex. (1,0,1,1,1,0) = (1,0, *, *, *, *) So subtuple (1,0) is in the tuple!
c.f. I don't need to know (1,0) is in (1,0,1,1,1,0) like this :
(1,0,1,1,1,0) = ( *, *, *, *, 1,0) so (1,0) is in (1,0,1,1,1,0).. => wrong one.
Upvotes: 4
Views: 3943
Reputation: 1912
main_tuple = (1, 2, 3, 4, 5)
subtuple = (1, 2)
if set(subtuple) <= set(main_tuple):
print('subtuple is part of the main tuple')
Look, you need to convert the tuple to set. If you maintain the tuple structure it doesn't work. Having a set, you need to check if your subtuple is less or equal than your main tuple.
MAIN_TUPLE = (1, 2, 3, 4, 5)
A = (1, 2) # Is a subtuple
B = (5, 3, 2) # Is a subtuple
C = (6, 7) # No
D = (1, 8) # No
Upvotes: 1
Reputation: 100
The documentation for the builtin sequence types says that the in
operation can do a subsequence check, but only for certain types:
Notes:
While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:
>>> "gg" in "eggs" True
So if your data is only integers between 0 and 255, you could convert to bytes to check:
>>>bytes((1,0)) in bytes((1,0,1,1,1,0))
True
For other types of data, this expression is a one-line way of iterating:
A = ('L', 'R')
B = ('L', 'R', 'L', 'L', 'L', 'R')
any(A == B[i:len(A) + i] for i in range(len(B) - len(A) + 1))
True
...though perhaps writing it out in a for loop would be easier to read.
These methods would catch (1, 0) if it comes anywhere in the second tuple, so the example you have labelled as the wrong one would be matched. If you only want to match if the first tuple is found starting with the first entry in the second tuple, then perhaps you could slice and compare:
>>> A = (1, 0)
>>> B = (1, 0, 1, 1, 1, 0)
>>> A == B[:len(A)]
True
Upvotes: 6