Re: Find last NZ in list
- To: mathgroup at smc.vnet.net
- Subject: [mg46163] Re: Find last NZ in list
- From: carlos at colorado.edu (Carlos Felippa)
- Date: Mon, 9 Feb 2004 05:54:11 -0500 (EST)
- References: <200402060915.EAA19244@smc.vnet.net> <c02cp5$54m$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
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.
- Follow-Ups:
- Re: Re: Find last NZ in list
- From: János Löbb <janos.lobb@yale.edu>
- Re: Re: Find last NZ in list
- References:
- Find last NZ in list
- From: carlos@colorado.edu (Carlos Felippa)
- Find last NZ in list