Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a list contains another list as a contiguous subsequence?

How can I test if a list contains another list (ie. it's a contiguous subsequence). Say there was a function called contains:

contains([1,2], [-1, 0, 1, 2]) # Returns [2, 3] (contains returns [start, end]) contains([1,3], [-1, 0, 1, 2]) # Returns False contains([1, 2], [[1, 2], 3]) # Returns False contains([[1, 2]], [[1, 2], 3]) # Returns [0, 0] 

Edit:

contains([2, 1], [-1, 0, 1, 2]) # Returns False contains([-1, 1, 2], [-1, 0, 1, 2]) # Returns False contains([0, 1, 2], [-1, 0, 1, 2]) # Returns [1, 3] 
like image 681
None Avatar asked Oct 02 '10 20:10

None


People also ask

How do you check if a list contains items from another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you check if a list contains another list in Python?

issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.

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

USE set. issubset() TO CHECK IF A LIST IS A SUBSET OF ANOTHER LIST Use set(list) to convert the lists to sets. Call set1. issubset(set2) to return a Boolean indicating whether set1 is a subset of set2.

How do you check if a list is a subset of another list C#?

You can simply check to see that the set difference between query2 and query1 is the empty set: var isSubset = ! query2. Except(query1).


2 Answers

If all items are unique, you can use sets.

>>> items = set([-1, 0, 1, 2]) >>> set([1, 2]).issubset(items) True >>> set([1, 3]).issubset(items) False 
like image 158
Thomas O Avatar answered Oct 16 '22 14:10

Thomas O


There's an all() and any() function to do this. To check if big contains ALL elements in small

result = all(elem in big for elem in small) 

To check if small contains ANY elements in big

result = any(elem in big for elem in small) 

the variable result would be boolean (TRUE/FALSE).

like image 20
ericyan3000 Avatar answered Oct 16 '22 12:10

ericyan3000