Re: Position of Last Element in List
- To: mathgroup at smc.vnet.net
- Subject: [mg94158] Re: Position of Last Element in List
- From: SigmundV <sigmundv at gmail.com>
- Date: Sat, 6 Dec 2008 06:13:50 -0500 (EST)
- References: <ghb02f$oho$1@smc.vnet.net> <ghb5dv$rmb$1@smc.vnet.net>
Hello Raffy, Excuse me, but I do not see what you want and what you would use it for. The sentence "the last position of an element at level 1 in a list" sounds a bit cryptic to me. Say that we have the list {{1, 2, 4, 6, -1}, {4, 10, 8, -2, 10}}, which is a list of lists. Here level 1 consists of the two lists {1, 2, 4, 6, -1} and {4, 10, 8, -2, 10}, right? How should "the last position of an element" be understood here? Regards, Sigmund On Dec 5, 1:05 pm, 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).