Skip to main content

coefficients - How to locate a list within a list?



for example f[{1,2,3,4},{2,3}]=True, f[{1,2,3,4},{2,3,4}]=True but f[{1,2,3,4},{2,4}]=False. Which function should I use because I don't want to reinvent the wheel. Thanks in advance



Answer



We may use pattern matching:


f[a_, {ss__}] := MatchQ[a, {___, ss, ___}]

Testing:


f[{1, 2, 3, 4}, {2, 3}]          (* True  *)
f[{1, 2, 3, 4}, {2, 3, 4}] (* True *)
f[{1, 2, 3, 4}, {2, 4}] (* False *)


This should work in any version of Mathematica and it is nearly equivalent in performance to SequencePosition: (as measured in version 10.1 under Windows)


f1[Range[10000], {5000, 5001, 5002}] // RepeatedTiming
f[Range[10000], {5000, 5001, 5002}] // RepeatedTiming


{0.000444, True}


{0.000475, True}



Comments