I have 2 lists: list_1 and list_2.
list_1: ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
I've
list_2: ['yeah', 'i', 'watched', 'the', 'world']
and
list_3: ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
I want to check if the elements in list_2
are present in list_1
in the same order, in this case
['yeah', 'i', 'watched', 'the', 'world']
regardless of the starting and ending position in the list_1.
However, when if I compare list_3 vs list_2, although all the elements from list_2 are present in list_3, they are ordered differently.
In the first case (list_1 vs list_2), the answer would be True. In the second case (list_3 vs list_2), the answer would be False.
CodePudding user response:
Here is the code. If you enter 2 list in the function, the function will check if all the elements in second list are inside first list with same order in both list.
list_1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list_2= ['yeah', 'i', 'watched', 'the', 'world']
list_3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
def check(ref_list, check_list):
matching=0
for i in range(len(ref_list)):
if check_list[0]==ref_list[i] and check_list[1]==ref_list[i 1]:
for j in range(len(check_list)):
if check_list[j]==ref_list[i j]:
matching=1
else:
matching=0
if j==len(check_list)-1:
if matching==1:
print("checking list Matched with reference")
return 0
else:
print("Didn't match")
return 0
if matching==0:
print("Didn't match")
return 0
check(list_1,list_2)
CodePudding user response:
Method:
start at beginning of list1
loop:
find position of word of list2 in remaining of list1.
Return False if not in list1.
def match( list2, list1):
i0 = 0 # start point in list1
for i2 in range( len( list2)):
for i1 in range( i0, len( list1)):
if list1[i1]==list2[i2]:
i0 = i1 # next search will start here
break
else:
return False # not found
return True # match
list1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list2= ['yeah', 'i', 'watched', 'the', 'world']
list3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
match( list2, list1) # return True
match( list2, list3) # return False