|
[Date Index]
[Thread Index]
[Author Index]
Re: First nonzero in list
- To: mathgroup at smc.vnet.net
- Subject: [mg110848] Re: First nonzero in list
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Thu, 8 Jul 2010 06:50:56 -0400 (EDT)
- References: <201007080713.DAA07701@smc.vnet.net>
Hi Steve,
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.
Hope this helps.
Regards,
Leonid
On Thu, Jul 8, 2010 at 11:13 AM, S. B. Gray <stevebg at roadrunner.com> wrote:
> I have lists such as
>
> th = {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}
>
> and I want to find the position of the last nonzero element (e.g. 3 at
> position 25). Trivial, but some poking around did not reveal a neat way.
>
> Anyone? Thank you.
>
> Steve Gray
>
>
Prev by Date:
Re: Pattern: x_List with conditions on elements
Next by Date:
Re: Pattern: x_List with conditions on elements
Previous by thread:
First nonzero in list
Next by thread:
Re: First nonzero in list
|