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: [mg94193] Re: Position of Last Element in List
  • From: Raffy <raffy at mac.com>
  • Date: Sat, 6 Dec 2008 19:57:57 -0500 (EST)
  • References: <200812051033.FAA25138@smc.vnet.net> <ghdmv8$fqo$1@smc.vnet.net>

On Dec 6, 3:16 am, Carl Woll <ca... at wolfram.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
>
> 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

Thanks, that's an interesting solution.

What are the chances that Position[]'s length argument, when negative,
would work from the end? ie. in a future version of Mathematica?

It seems silly that such a task is so slow in Mathematica.   Almost
every solution requires iterating over all the elements, whereas the
actual algorithm should never process beyond the first occurrence
(from the end).


  • Prev by Date: Re: Drop elements from 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