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: [mg94183] Re: [mg94130] Position of Last Element in List
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Sat, 6 Dec 2008 06:18:25 -0500 (EST)
  • References: <200812051033.FAA25138@smc.vnet.net>

On 5 Dec 2008, at 19:33, 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 slightly faster on my 2.2 gigahertz MacBook:

lastPos1[v_List, p_] :=
  With[{m = Last[Split[Unitize[v - p]]]}, If[m[[-1]] === 0, 1,  
Length[m] + 1]]

In[3]:= v = Range[1000000];
Do[lastPos[v, 900000], {100}] // Timing
Out[4]= {11.4684, Null}
In[5]:=
Do[lastPos1[v, 900000], {100}] // Timing
Out[5]= {9.56562, Null}

Note that if p is not present instead of returning $Failed this  
returns the length of the list + 1.

Andrzej Kozlowski

Andrzej Kozlowski


  • Prev by Date: Re: InverseLaplaceTransform different solution in Mathematica 6 and
  • Next by Date: Re: Re: A plot of Sign[x]
  • Previous by thread: Re: Position of Last Element in List
  • Next by thread: Re: Position of Last Element in List