Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for the presence of a sub-list

Can you provide me a performing (possibly idiomatic) way to check if a list A is a sublist of a given list B?

E.g.

isSubList(List(1,2), List(1,2,3,4)) // => true
isSubList(List(1,2), List(5,6,7,8)) // => false 
like image 215
Aslan986 Avatar asked Aug 28 '14 09:08

Aslan986


People also ask

How do you check if a list contains a sublist?

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 value exists in a nested list?

Use the any() function to check if a value exists in a two-dimensional list, e.g. if any('value' in nested_list for nested_list in my_2d_list): . The any() function will return True if the value exists in the list and False otherwise.

How do you find the sub list in Python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

How do I check if an item is present in a list?

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.


1 Answers

One way would be to use forall and contains:

scala>   List(1, 2).forall(List(1, 2, 3, 4).contains)
res3: Boolean = true

scala>   List(1, 2).forall(List(5, 6, 7, 8).contains)
res4: Boolean = false

scala>   List(1, 2).forall(List(5, 6, 2, 9).contains)
res5: Boolean = false

Note that this approach doesn't consider ordering:

scala>   List(1, 2).forall(List(2, 1).contains)
res6: Boolean = true

Probably you could use also Sets and intersect, but I think this way is preferable.

like image 163
Ende Neu Avatar answered Sep 23 '22 04:09

Ende Neu