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