search a list in another list using Python

时光怂恿深爱的人放手 提交于 2021-01-29 06:55:43

问题


I am trying to write the sublist search algorithm using Python.

For reference : https://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list/

Here is my code:

def sublist(arr1,arr2):
i = 0
j = 0
k = 0
if len(arr1) == 0:
    print('List1 Empty')
if len(arr2) == 0:
    print('List 2 Empty')
for j in range(0,len(arr2)):
    for i in range(0,len(arr1)):
        if arr1[i] != arr2[j]:
            break
        while arr1[i] == arr2 [j]:
            if i == len(arr1) - 1:
                return True
            i = i + 1
            j = j + 1
            if i == len(arr1):
                return False
        return False 

I am sure this code can be optimized and reduce time complexity. Because of while loop, does the complexity increase than O(m*n)? Beginner student here


回答1:


The following compares the first portion of arr2 to arr1, to determine if they are equal. If so, or any recursive call on some offset of arr2 returns true, then return true. Otherwise, if at any point the sublist of the original arr2 is shorter than arr1, return False.

def sublist(arr1, arr2):
    if len(arr2) < len(arr1):
        return False
    return arr1 == arr2[:len(arr1)] or sublist(arr1, arr2[1:])



回答2:


I think that this works better:

def sublist(arr1,arr2):
  "This fuction checks if arr1 is a sublist of arr2."
  for i in range(len(arr2)):
    part=arr2[i:] # part is a list which all the elements from i to the end of arr2
    if len(part)<len(arr1):
      return False
    if arr1==part[:len(arr1)]: # if arr1 is in the beginning of part return True
      return True
  return False


来源:https://stackoverflow.com/questions/55029591/search-a-list-in-another-list-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!