MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: position of sequence of numbers in list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg106995] Re: position of sequence of numbers in list
  • From: Raffy <raffy at mac.com>
  • Date: Sun, 31 Jan 2010 05:56:10 -0500 (EST)
  • References: <hk17lo$ogf$1@smc.vnet.net>

On Jan 30, 4:11 am, JB <jke... at gmail.com> wrote:
> Hi,
>
> What is the most efficient way to find the position of the beginning
> of a sequence of numbers from a list?
>
> I found a couple of ways:
>
> find 3,4 in list={1,2,3,4,5};
>
>  1.   pos=Intersection[Position[list,3],(Position[list,4])+1]
>
>  2.   pos=Position[Partition[list,2,1],{3,4}]
>
> Are there other ways to do this?
> What is the best way when dealing with large lists?
>
> Thanks,
> JB

Well, the {3,4} pattern must start with the first element of the
sublist.  You can ignore the last position since the following 4 would
beyond the end of the list.

pos = Flatten@Position[Most[list], 3, {1}];

>From these positions, find the ones with a 4 in the next position:

pos = vPos[[Flatten@Position[list[[vPos + 1]], 4, {1}]]];

You could generalize this to repeating the above statement at
increasing offsets.

list = {1, 2, 3, 4, 5};
sub = {3, 4};

pos = Flatten@Position[Drop[list, 1 - Length[sub]], First[sub], {1}];
Do[pos = pos[[Flatten@Position[list[[pos + i - 1]], sub[[i]], {1}]]],
{i, 2, Length[sub]}];

Or, you could generalize it by finding the start position of the
sublist and then just extracting the following list to see if they
match the remainder of the sublist.

pos = Flatten@Position[Drop[list, 1 - Length[sub]], First[sub], {1}];
pos = Pick[pos, list[[# + 1 ;; # + Length[sub] - 1]] & /@ pos, Rest
[sub]]

Additionally, you'll want to verify that the Length[sublist] > 0.


  • Prev by Date: Re: position of sequence of numbers in list
  • Next by Date: Re: position of sequence of numbers in list
  • Previous by thread: Re: position of sequence of numbers in list
  • Next by thread: Problem with ContourPlot3D