Re: First nonzero in list

• To: mathgroup at smc.vnet.net
• Subject: [mg110867] Re: First nonzero in list
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Thu, 8 Jul 2010 20:35:26 -0400 (EDT)

```On 7/8/10 at 6:50 AM, lshifr at gmail.com (Leonid Shifrin) wrote:

>Here are a couple of ways:

>In[6]:= inp = {227, 342, 527, 0, 670, 730, 703, 0, 0, 649, 687, 614,
>570, 501, 462, 402, 325, 254, 189, 99, 81, 36, 9, 8, 3, 0, 0, 0, 0,
>0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
>0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

>In[8]:= inp /. {x___, 0 ..} :> Length[{x}]

>Out[8]= 25

>In[10]:= Length[inp] - LengthWhile[Reverse[inp], # == 0 &]

>Out[10]= 25

>The first solution is more elegant but impractical for large lists.
>The second is reasonably efficient also for large lists. There are
>many more solutions of course.

Here is another way:

SparseArray[inp] /. SparseArray[_, _, _, {_, {_, {___, a_}}, _}]
-> a

This should be faster for long lists that are sufficiently
sparse than the second method you propose above. But it will
definitely be slower if list is dense (has only a few zeros).

```

• Prev by Date: Re: First nonzero in list
• Next by Date: Re: replacement x->y except in Exp[x]
• Previous by thread: Re: First nonzero in list
• Next by thread: Re: First nonzero in list