5
$\begingroup$

I want to see if a specific list is part of another list and get either True or False.

As an example:

list1={1,2,3,4}
list2={1,2}
list3={1,3}

list2 is now part of list1 and the argument should be True, while list3 isn't part of list1 as it is not the correct order.

I tried several Pattern Mactching Functions like MemberQ, which only works for elements not for lists. SubsetQ is pretty close, but doesn't check the correct order as well as ContainsX.

My workaround is to convert the list into a string and use StringContainsQ, but I think there might be a better solution as well.

$\endgroup$
3
  • 1
    $\begingroup$ SequenceCases[list1, #] & /@ {list2, list3} $\endgroup$
    – cvgmt
    Commented Mar 13 at 13:31
  • 1
    $\begingroup$ inItQ[alist_,anotherlist_]:=MatchQ[alist,Join[{___},anotherlist,{___}]] followed by inItQ[list1,list2] and inItQ[list2,list3] $\endgroup$
    – Bill
    Commented Mar 13 at 13:43
  • 1
    $\begingroup$ Should llist4={2,1} give True or False? $\endgroup$
    – user1066
    Commented Mar 13 at 15:16

3 Answers 3

6
$\begingroup$
a = {1, 2, 3, 4};   
b = {1, 2};
c = {1, 3};

1.

Using SequenceCases

SequenceCases[a, b] == {b}

True

SequenceCases[a, c] == {c}

False

2.

Using SequenceCount

SequenceCount[a, #] > 0 & /@ {b, c}

{True, False}

3.

Using Partition

MemberQ[#] @ Partition[a, 2, 1] & /@ {b, c}

{True, False}

Partition should be significantly faster with long lists than one of the Sequence-functions

$\endgroup$
3
$\begingroup$
Clear[f, g]

f[alist_?VectorQ, blist_?VectorQ] := 
 Subsequences[alist, {Length@blist}] // MemberQ[blist]

g = LongestCommonSubsequence[#1, #2] === #2 &;

Test:

list1 = {1, 2, 3, 4};
list2 = {1, 2};
list3 = {1, 3};
list4 = {1, 2, 3};

p = Permutations[{list1, list2, list3, list4}, {2}]

Transpose[{p, Apply[f, p, {1}]}] // Grid

enter image description here


Similarly: Transpose[{p, g @@@ p}] // Grid

$\endgroup$
3
$\begingroup$
l1 = {1, 2, 3, 4};
l2 = {1, 2};
l3 = {1, 3};

Another way using ReplaceList:

patt = PatternSequence[##] &;

f = ReplaceList[#1, {___, s : patt @@ #2, ___} :> {s}] =!= {} &;

f @@ {l1, l2}

(*True*)

f @@ {l1, l3}

(*False*)

Or using PositionIndex:

f = Det@Differences@Lookup[PositionIndex[#1], #2] == 1 &;

f @@ {l1, l2}

(*True*)

f @@ {l1, l3}

(*False*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.