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: [mg94173] Re: Position of Last Element in List
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Sat, 6 Dec 2008 06:16:34 -0500 (EST)
  • References: <ghb02f$oho$1@smc.vnet.net> <ghb5dv$rmb$1@smc.vnet.net>

On Dec 5, 4:05 am, Szabolcs Horv=E1t <szhor... at gmail.com> wrote:
> 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).

This isn't as fast as Szabolcs' lastPos and is quite arcane,
but it's still about twice as fast as the original lastPos
and will handle mixed integers and reals.

lastPoz[vec_,val_] := Block[{r = Range@Length@vec},
r[[ SparseArray[vec,Automatic,val] /.
    SparseArray[_,_,_,p_] :> Flatten@p[[2,2]] ]] = 0;
Last[SparseArray[r] /. SparseArray[_,_,_,p_] :> p[[3]] /. {}->{0} ]]


  • Prev by Date: Re: Position of Last Element in List
  • Next by Date: Re: Position of Last Element in List
  • Previous by thread: Re: Position of Last Element in List
  • Next by thread: Re: Position of Last Element in List