Re: Position of Last Element in List
- To: mathgroup at smc.vnet.net
- Subject: [mg94175] Re: [mg94130] Position of Last Element in List
- From: Carl Woll <carlw at wolfram.com>
- Date: Sat, 6 Dec 2008 06:16:56 -0500 (EST)
- References: <200812051033.FAA25138@smc.vnet.net>
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 > > If v is a packed list of integers, then something like the following is more than an order of magnitude faster: lastp[v_List, p_Integer] := First @ Ordering[Clip[v, {p,p}, {p-1,p-1}], -1] Some postprocessing is needed if p isn't in v, and the result is the position starting from the beginning instead of the end. Carl Woll Wolfram Research
- References:
- Position of Last Element in List
- From: Raffy <raffy@mac.com>
- Position of Last Element in List