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: [mg106997] Re: position of sequence of numbers in list
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Sun, 31 Jan 2010 05:56:32 -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

pne[vec,val] returns a list of the positions in vec that are NOT EQUAL
to val.

peq[vec,val] returns a list of the positions in vec that are EQUAL to
val. It's slower than pne but faster than the built-in Position.

Both pne and peq return simple lists, not the list-of-lists that
Position returns.

pne[vec_,val_] := SparseArray[vec,Automatic,val] /.
SparseArray[_, _, _, p_] :> Flatten@p[[2,2]]

peq[vec_,val_] := Block[{r = Range@Length@vec}, r[[pne[vec,val]]] = 0;
SparseArray[r] /. SparseArray[_, _, _, p_] :> p[[3]]]

list = Table[Random[Integer,{1,5}],{1*^6}];

Timing@Length[a = Intersection[Position[list,3],Position[list,4]-1]]
{1.09 Second, 39674}

Timing@Length[b = Position[Partition[list,2,1],{3,4}]]
{1.4 Second, 39674}

Timing@Length[c = Intersection[peq[list,3],peq[list,4]-1]]
{0.44 Second, 39674}

SameQ[a,b,Transpose@{c}]
True


  • Prev by Date: Prime Rotating Diagram
  • 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: Re: position of sequence of numbers in list