Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: Find last NZ in list


I see...  I was a little naive...
Here is a better one - still not using explicit loop.

nn = 20000
a = Table[0, {nn}];
a[[666]] = dante
a[[665]] = lucifer
a[[111]] = Maria


Timing[Last[Position[a, x_ /; (x ­ 0 || Head[x] == Symbol)]]]

{0.54 Second, {666}}

Mea culpa for the previous one.

J?nos


On Feb 9, 2004, at 5:54 AM, Carlos Felippa wrote:

> Many thanks for the submissions.  Here is a comparison of five
> functions and their timings on a mac g4.
>
> FindLastNonzero[a_]:=Module[{n=Length[a]},
>     For [i=n,i>0,i--, If [a[[i]]==0,Continue[],Return[i],
>     Return[i]]]; Return[0]];  (* CAF *)
> FindLastNonzero1[a_]:=Module[{n=Length[a]},
>     For [i=n,i>0,i--, If [a[[i]]!=0,Return[i],Continue[],
>     Return[i]]]; Return[0]];  (* CAF *)
> FindLastNonzero2[a_]:=Catch[Do[If[a[[i]]=! 
> =0,Throw[i]],{i,Length[a],1,-1}];0];
>         (* Andrzej Kozlowski *)
> FindLastNonzero3[a_]:=First[Position[a, _?(# == 0 &)]] - 1;    (*
> J?nos Lobb *)
> FindLastNonzero4[lst_]:=
>   Module[{tmp=DeleteCases[lst,0]},
>     If[Length[tmp]!=0,Last[tmp],0]  ];  (* Bo Le *)
> FindLastNonZero5[liste_] :=
>   If[Position[(StringMatchQ[#1, "0"] & ) /@
>       ToString /@ liste, False] != {},
>    Last[Position[(StringMatchQ[#1, "0"] & ) /@
>        ToString /@ liste, False]][[1]], 0];  (* Florian Jaccard *)
>
> nn=20000;  a=Table[0,{nn}]; a[[666]]=dante;
> Print[Timing[FindLastNonzero  [a]]];
> Print[Timing[FindLastNonzero1[a]]];
> Print[Timing[FindLastNonzero2[a]]];
> Print[Timing[FindLastNonzero3[a]]];    (* fails on this example *)
> Print[Timing[FindLastNonzero4[a]]];    (* returns entry, not index *)
> (* Print[Timing[FindLastNonzero5[a]]];  does not work *)
>
> {0.55 Second,666}
> {0.4 Second,666}
> {0.133333 Second,666}
> {0.2 Second,{0}}
> {0.0333333 Second,dante}
>
> FindLastNonzero4 is fastest but requires another Position search for
> the entry index .  Of those that work in one shot, FindLastNonzero2 is
> fastest.
>
> The most elegant functional solution would be to say
>   i = FirstPosition[Reverse[a],!=0];
> as a built in function.  But this doesnt exist.
>
>
-------------------------------------------------
clear perl code is better than unclear awk code; but NOTHING comes  
close to unclear perl code
http://www.faqs.org/faqs/computer-lang/awk/faq/


  • Prev by Date: Re: RE: Formal Definition of the Term "Form"
  • Next by Date: Re: Polylogarithm Integration - Bis
  • Previous by thread: Re: Find last NZ in list
  • Next by thread: Specifying arguments inside nested functions