구마왕
구마왕

Reputation: 498

Python:: How to find out the subtuple of a tuple is in the tuple?

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

Answers (2)

Lucas Vazquez
Lucas Vazquez

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

Adam Schettenhelm
Adam Schettenhelm

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:

  1. 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

Related Questions