1

I have a list of tuples of various lengths and need to find a method to check if there are tuples that are an exact, ordered subsequence of one another. I will show with an example what I mean in this context:

Assume I have the following tuples:

t1 = (37, 5, 3, 22, 1)
t2 = (3, 5, 22)
t3 = (3, 22, 1)
t4 = (37, 41, 19)

Let's call the hypothetical function check_sub_tuple. Then the function should give the following outputs:

  • check_sub_tuple(t1, t2) = False, (t2 is not a subtuple of t1)
  • check_sub_tuple(t1, t3) = True, (t3 is a subtuple of t1)
  • check_sub_tuple(ti, tj) = False for all other pairs of tuples ti and tj in the example

Question 1: Is there existing Python functionality for this? I know I could do this:

set(my_tuple_2).issubset(my_tuple_1)

But this just checks if the elements of one tuple are contained in the other, I also need the order to be the same.

Question 2: How can I do the exact same thing for lists instead of tuples?

4
  • Do you mean "subsequence"? Subsets are unordered. Commented May 19, 2021 at 21:52
  • So your input is a list of lists/tuples? What about the exact output in the example then? Just to confirm. Commented May 19, 2021 at 21:55
  • @Daniel Hao True, I either have a list with only lists or a list with only tuples, and I need to check which pairs of lists/tuples are subsequences of another Commented May 19, 2021 at 22:00
  • In case tuples consist of integers in range(0, 256), you can use bytes(ti) in bytes(tj). Commented May 19, 2021 at 22:01

1 Answer 1

0

I think you could use this:

t1 = [37, 5, 3, 22, 1]
t2 = [3, 22, 1]

any(t2 == t1[i:i+len(t2)] for i in range(0,len(t1)))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.