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: [mg94174] Re: [mg94130] Position of Last Element in List
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Sat, 6 Dec 2008 06:16:45 -0500 (EST)
  • References: <200812051033.FAA25138@smc.vnet.net> <3E66AD62-46BB-483B-9A30-E33029DA4017@mimuw.edu.pl>

Here is a slightly improved version (essentially only in the case when  
p is the last element of the list):

lastPos2[ls_, p_] := If[Last[ls] === p, 1,  
Length[Last[Split[Unitize[ls - p]]]] + 1]

Andrzej Kozlowski


On 5 Dec 2008, at 23:35, Andrzej Kozlowski wrote:

>
> 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: Position of Last Element in List
  • 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