简体   繁体   English

检查一个列表是否是另一个列表的一部分

[英]Checking if a a list is a segment of another list

I want to make a module in Mathematica that return true if the first list (L1) is in the second list (L2) assuming that the length of L2 is greater than the length of L1. 我想在Mathematica中制作一个模块,如果第一个列表(L1)在第二个列表(L2)中,则假定L2的长度大于L1的长度,则返回true。 I did it in this way, the problem is that always return False and I don't know why. 我是以这种方式完成的,问题是总是返回False,而我不知道为什么。 EDIT: I have solved a problem: I wrote "if" instead of "If". 编辑:我已经解决了一个问题:我写了“如果”而不是“如果”。 Now I get an infinitely loop. 现在我得到一个无限循环。

isSegment[L1_List, L2_List] := Module[{i, j},   For[i = 1, i + Length[L1] - 1 <= Length[L2],
       For[j = 1, j <= Length[L1],
    If[L2[[i + j - 1]] != L1[[j]], Break;];
    j++;
    ];
       If[j == Length[L1] + 1,
    Return[ True];];
       i++;    ];   Return [False];   ]

This is likely to be one of the cleanest and fastest general methods available: 这可能是最干净,最快的常规方法之一:

isSegment[{L1__}, L2_List] := MatchQ[L2, {___, L1, ___}]

isSegment[{3, 4, 5}, Range@10]
 True 

For a list of all Real or Integer values you could adapt the methods shown here for maximum speed. 有关所有RealInteger数值的列表,您可以调整此处显示的方法以获得最大速度。


user writes: 用户写道:

Thanks, it is a good way, but what I want is to correct my code not to have a new one because it is an exercise for school and in the statement it is said that we must use For loops. 谢谢,这是一个好方法,但是我要纠正我的代码以使其没有新的代码,因为这是学校的一种练习,并且在语句中说必须使用For循环。

It appears that there is confusion over the syntax of Break[] and the function of Return . 似乎对Break[]的语法和Return的功能感到困惑。 To correct the code I replaced Break with Break[] and Return with Throw & Catch . 为了更正代码,我将Break替换为Break[]并将Return替换为ThrowCatch

isSegment[L1_List, L2_List] :=
 Catch @ Module[{i, j},
   For[i = 1, i + Length[L1] - 1 <= Length[L2],
    For[j = 1, j <= Length[L1], 
     If[L2[[i + j - 1]] != L1[[j]], Break[];]; j++;];
    If[j == Length[L1] + 1, Throw[True];];
    i++;]; Throw[False];
   ]

我通常会使用以下方法解决此问题:

SegmentQ[l1_List, l2_List] := MemberQ[Partition[l2, Length @ l1, 1], l1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM