I want to write a function that determines if a sublist exists in a larger list.
list1 = [1,0,1,1,1,0,0]
list2 = [1,0,1,0,1,0,1]
#Should return true
sublistExists(list1, [1,1,1])
#Should return false
sublistExists(list2, [1,1,1])
Is there a Python function that can do this?
Let's get a bit functional, shall we? :)
Note that
any()
will stop on first match of sublst within lst - or fail if there is no match, after O(m*n) opsThe efficient way to do this is to use the Boyer-Moore algorithm, as Mark Byers suggests. I have done it already here: Boyer-Moore search of a list for a sub-list in Python, but will paste the code here. It's based on the Wikipedia article.
The
search()
function returns the index of the sub-list being searched for, or -1 on failure.Here is the example from the question:
Output:
if iam understanding this correctly, you have a larger list, like :
then there are other lists
and then i append the lists B and C to list A
so when i print list_A
i get the following output
now that i want to check if the sublist exists:
this will give you 'True' if you have any sublist inside the larger list.
If you are sure that your inputs will only contain the single digits 0 and 1 then you can convert to strings:
This creates two strings so it is not the most efficient solution but since it takes advantage of the optimized string searching algorithm in Python it's probably good enough for most purposes.
If efficiency is very important you can look at the Boyer-Moore string searching algorithm, adapted to work on lists.
A naive search has O(n*m) worst case but can be suitable if you cannot use the converting to string trick and you don't need to worry about performance.