1

Is there a Pythonic way of determining if a tuple is a slice of another tuple (and not only a subset)?

For example, if I have the following tuples:

t1 = (2, 3, 4)
t2 = (1, 2, 3, 4, 5)
t3 = (3, 4, 2, 5)

then t1 is a slice of t2 but only a subset of t3. I'm looking for something like "t1 in t2". Window-based shifting of one tuple along another one is "implementable" but there may be a more efficient way that I don't know.

  • Conceptually I don't think you'll do better than the "Window-based shifting" you suggest – Chris_Rands Jun 26 '20 at 10:38
  • The question against which this question has been marked as a duplicate is not a duplicate of this question. That question is about extracting the sub-patterns. Similar but slightly different. – Amal K Jun 26 '20 at 10:59
  • I made an experiment with Boyer Moore, however, it was even slower than the "bonus subfinder" contained in one answer to the linked similar question - maybe due to the fact that the bad character table for int tuples cannot be an array or a list (which would result in a vast memory consumption) but has to be a dictionary. – Stephan Geue Jul 11 '20 at 20:26

1 Answers1

1

Convert both tuples to strings and then use the in operator to check if one is a substring of another.

' '.join(map(str, t1)) in ' '.join(map(str, t2))

Do note the space in the string on which join().is called. If you don't include the space, this could happen:

''.join(map(str, (1, 2, 3))) in ''.join(map(str, (1, 23, 4)))
# 123 in 1234 == True

Amal K
  • 4,359
  • 2
  • 22
  • 44
  • How is this quicker than window sliding technique? – 0buz Jun 26 '20 at 10:57
  • It isn't, but it abstracts away the conditionals and iterations and is a more "elegant" and concise one-line alternative if you will. – Amal K Jun 26 '20 at 11:07