Re: Position of Last Element in List
- To: mathgroup at smc.vnet.net
- Subject: [mg94179] Re: Position of Last Element in List
- From: thomas <thomas.muench at gmail.com>
- Date: Sat, 6 Dec 2008 06:17:40 -0500 (EST)
- References: <ghb02f$oho$1@smc.vnet.net>
This is about 8-9 times faster, but only for numeric data. For non- numeric data it is very slow: lastPos1[v_List,elem_]:=SparseArray[Unitize[v-elem]-1]/.SparseArray [_,_,_,p_]:>Flatten[p[[2,2]]][[-1]] The trick here is that in its internal structure, SparseArray stores the positions of non-zero elements within its forth argument (named p above). Unitize[v-elem] is 0 where-ever elem occurs, 1 everywhere else, and by subtracting 1 only your desired element becomes non-zero. Unitize evaluates to 1 only for non-zero *numerical* data, otherwise it remains unevaluated. This is what makes the whole thing slow for non-numerical data. Best, Thomas On Dec 5, 11:33 am, Raffy <ra... at mac.com> 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