0

Hi I'm trying to do a sub-list search algorithm in python that I found here, need some efficient solutions in terms of time complexity. What I tried is:

l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]

l1_index = 0
l = len(l1)

sublist = []

for i in range(len(l2)):
    if l1[l1_index] == l2[i]:
        sublist.append(l2[i])
        l1_index += 1
        print("found")
        if len(sublist) == l:
            break
        continue
    else:
        print("not found")
        l1_index = 0
  • From the same site: https://www.geeksforgeeks.org/python-check-if-one-list-is-subset-of-other/ – PM 77-1 Jun 20 '20 at 18:53
  • Does this answer your question? [How can I verify if one list is a subset of another?](https://stackoverflow.com/questions/16579085/how-can-i-verify-if-one-list-is-a-subset-of-another) – PM 77-1 Jun 20 '20 at 18:54
  • @PM77-1 solution with all() works. Thanks – vineet singh Jun 20 '20 at 19:00

2 Answers2

0

Convert l1 and l2 to strings, and then do the search:

l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]
l1 = str(l1)
l2 = str(l2)
# This will return a string of the data only without the '[',']'
l1 = l1.split('[')[1].split(']')[0]
l2 = l2.split('[')[1].split(']')[0]
# Using string find function
if l2.find(l1) > 0 :
    print('l1 is a sublist of l2')
0

Here is what you can do:

l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]

found = False
for i in range(len(l2)-len(l1)+1):
    if l2[i:i+len(l1)] == l1:
        found = True

if found:
    print('found')
else:
    print('not found')

Output:

found

Another way:

l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]

if str(l1)[1:-1] in str(l2)[1:-1]:
    print('found')
else:
    print('not found')

Output:

found
Ann Zen
  • 25,080
  • 7
  • 31
  • 51