问题
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