Skip to content Skip to sidebar Skip to footer

Search A List In Another List Using Python

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:

Solution 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.

defsublist(arr1, arr2):
    iflen(arr2) < len(arr1):
        returnFalsereturn arr1 == arr2[:len(arr1)] or sublist(arr1, arr2[1:])

Solution 2:

I think that this works better:

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

Post a Comment for "Search A List In Another List Using Python"