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?

Peter
  • 722
  • 6
  • 24

1 Answers1

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)))
CAIO WANDERLEY
  • 313
  • 2
  • 9