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
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.
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.
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.
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.
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 Set
s and intersect
, but I think this way is preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With