Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: First nonzero in list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110862] Re: First nonzero in list
  • From: "gianpf" <jean.pellegri at orange.fr>
  • Date: Thu, 8 Jul 2010 20:34:32 -0400 (EDT)
  • References: <201007080713.DAA07701@smc.vnet.net> <i14ai8$g0d$1@smc.vnet.net>

Salut

In   :   Last[Position[th, t : _Integer /; Not[t == 0]]]

Out  :  25

where

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}

Ciao

jean




"Leonid Shifrin" <lshifr at gmail.com> a =E9crit dans le message de
news:i14ai8$g0d$1 at 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 mor=
e
> 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 wa=
y.
>>
>> Anyone? Thank you.
>>
>> Steve Gray
>>
>>



  • Prev by Date: Re: FindMinimum numerical constraint functions
  • Next by Date: Re: FittedModel object type
  • Previous by thread: Re: First nonzero in list
  • Next by thread: Re: First nonzero in list