MathGroup Archive 2008

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

Search the Archive

Re: Position of Last Element in List

  • To: mathgroup at smc.vnet.net
  • Subject: [mg94148] Re: Position of Last Element in List
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Fri, 5 Dec 2008 07:05:27 -0500 (EST)
  • Organization: University of Bergen
  • References: <ghb02f$oho$1@smc.vnet.net>

Raffy wrote:
> I'm looking for the fastest way to find the last position of an
> element at level 1 in a list.
> 
> The fastest way, which is still extremely bloated and extremely slow,
> appears to be:
> 
> lastPos[v_List,p_:True,default_:$Failed]:=(
> $Temp=Position[Reverse[v],p,{1},1,Heads->False];
> If[Length[$Temp]>0,$Temp[[1,1]],default]
> );
> 
> Any suggestions?
> 
> Use the following code to compare against lastPos:
> 
> v = Range[1000000];
> Do[lastPos[v,900000],{100}]//Timing
> 

This is about 4-5 times faster on my machine (possibly because it avoids 
unpacking the array):

lastPos =
  Compile[{{v, _Integer, 1}, {e, _Integer, 0}},
   Module[{i = Length[v]}, While[i > 0 && e != v[[i]], i--]; i]]

But it only works with lists of integers (it's possible to write a 
similar function for reals).


  • Prev by Date: Re: A plot of Sign[x]
  • Next by Date: Re: assignment problerm
  • Previous by thread: Re: Position of Last Element in List
  • Next by thread: Re: Position of Last Element in List