TransWikia.com

List X is a starter of List Y

Mathematica Asked by imida k on April 11, 2021

For lists X and Y,
let’s define a term ‘X is a starter of Y‘ to be
there exist a list Z such that Y = Join[X,Z]‘.

Until now I’ve used following code for ‘X is a starter of Y

Length[X]<=Length[Y] && X==Take[Y,Length[X]]

In case Length[X] > Length[Y], the expression Take[Y,Length[X]] produces an error. So the codes became messy.

Above code doesn’t look efficient nor beautiful. Is there other good one?

2 Answers

Note that your implementation

ClearAll[preFixQ1]
preFixQ1[x_, y_] := Length[x] <= Length[y] && x == Take[y,Length[x]]

should work without error because if the test Length[x] <= Length[y] fails And returns False without executing the second test. In fact, internal GeneralUtilities`PrefixQ is implemented the same way.

A cleaner alternative is to wrap the second argument of Take with UpTo and ( as suggested by imida k in comments) remove the length test:

preFixQ[x_, y_] :=  x == Take[y, UpTo@Length[x]]

Examples:

preFixQ[Range[3], Range[5]]
True
preFixQ[Range[6], Range[5]]
False

And alternative way to use MatchQ:

ClearAll[startsWith]
startsWith = MatchQ[Append[___] @ #2] @ # &;

{a, b, c} ~ startsWith ~ {a, b}
True
{a, b, c} ~ startsWith ~ {b, a}
False
{a, b, c} ~ startsWith ~ {a, b, c, d}
False

Correct answer by kglr on April 11, 2021

You may simply use a pattern for this:

x = {1, 2};
y = {1, 2, 10, 20};
MatchQ[y, {PatternSequence @@ x, ___}]
y = {0, 1, 2, 10, 20};
MatchQ[y, {PatternSequence @@ x, ___}]
y = {1};
MatchQ[y, {PatternSequence @@ x, ___}]

enter image description here

Answered by Daniel Huber on April 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP