3

My question is different with the typical one. Assume we have,

X = ['123', '456', '789']

And, we want to find whether another list is in X with exact same order. For example,

A = ['123', '456']
# should return True since A in X with same order
B = ['456', '123']
# should return False since elements in B are not in same order with X
C = ['123', '789']
# should return False since elements in C are not adjacent in X

Can anyone give me any idea?

Simon Beckham
  • 67
  • 1
  • 4

3 Answers3

7

Python 2:

def is_a_in_x(A, X):
  for i in xrange(len(X) - len(A) + 1):
    if A == X[i:i+len(A)]: return True
  return False

Python 3:

def is_a_in_x(A, X):
  for i in range(len(X) - len(A) + 1):
    if A == X[i:i+len(A)]: return True
  return False
Jimmy Huch
  • 4,400
  • 7
  • 29
  • 34
0
def foo(your_list, your_main_list):
    list_len = len(your_list)
    for i, item in enumerate(your_list):
        if your_main_list[i] == item: 
            if i + 1 == list_len:
                return True
        else:
            return False
Yonatan Kiron
  • 2,718
  • 1
  • 20
  • 25
-1

One possible solution if your numbers are always three digit:

x = ['123', '456', '789']

A = ['123', '456']
''.join(A) in ''.join(x)

B = ['456', '123']
''.join(B) in ''.join(x)

C = ['123', '789']
''.join(C) in ''.join(x)

Although, prone to bugs for example:

D = ['1', '23']
''.join(D) in ''.join(x)


outputs True
Kartik Anand
  • 4,513
  • 5
  • 41
  • 72