Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for presence of a sliced list in Python

Tags:

python

list

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?

like image 494
Jonathan Avatar asked Jul 22 '10 21:07

Jonathan


People also ask

How do you check if an item exists in a list Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you check if a list is present in another list in Python?

all() method # Program to check the list contains elements of another list # List1 List1 = ['python' , 'javascript', 'csharp', 'go', 'c', 'c++'] # List2 List2 = ['csharp1' , 'go', 'python'] check = all(item in List1 for item in List2) if check is True: print("The list {} contains all elements of the list {}".

How do you check if an element is not in a list Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.

How is the list sliced in Python?

With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.


1 Answers

Let's get a bit functional, shall we? :)

def contains_sublist(lst, sublst):     n = len(sublst)     return any((sublst == lst[i:i+n]) for i in xrange(len(lst)-n+1)) 

Note that any() will stop on first match of sublst within lst - or fail if there is no match, after O(m*n) ops

like image 155
Nas Banov Avatar answered Oct 07 '22 17:10

Nas Banov