Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Identify runs in list

0 views
Skip to first unread message

skor...@gmail.com

unread,
Oct 3, 2009, 10:21:49 PM10/3/09
to
Hi all,

I have a data structure in a list as in: [0 0 0 3 0 5 0 0 0 0 1 0 4 0
5 0 0 7 0 0 0 0 0 12 0 0 4]

I would like to extract three list from this data:

1) runsOfZero: [3 4 5]
2) runsOfNonZero: [3 8 4]
3) SumOfRunsOfNonZero: [8 17 16]

Any suggestions would be appreciated

Chris Rebert

unread,
Oct 3, 2009, 10:36:50 PM10/3/09
to skor...@gmail.com, pytho...@python.org

Since this sounds like homework, I won't give actual code, but here's
a gameplan:

1. Split the list into sublists based on where the runs of zeros stop and start.
2. Categorize the sublists and place them into lists-of-lists based on
whether they have nonzero entries. To do the categorization, you'll
have to iterate over the original list and track how many previous 0s
you've seen consecutively.
3. Use len() on the nonzero lists to get their length; puts the
results into a list (runsOfNonZero)
4. Use sum() on the nonzero lists to get their sums, and put the
results into another list (SumOfRunsOfNonZero)
5. Use len() on the all-zero lists to get their length and put the
results into a list (runsOfZero)

Cheers,
Chris
--
http://blog.rebertia.com

skor...@gmail.com

unread,
Oct 3, 2009, 10:53:22 PM10/3/09
to
On Oct 3, 10:36 pm, Chris Rebert <c...@rebertia.com> wrote:

Thanks Chris, Not homework but self learning. Also, forgot to mention
that I only count runs greater than 3 (zeros). I will now look over
your suggestions. Thanks again

Chris Rebert

unread,
Oct 3, 2009, 11:07:44 PM10/3/09
to skor...@gmail.com, pytho...@python.org
On Sat, Oct 3, 2009 at 7:53 PM, skor...@gmail.com <skor...@gmail.com> wrote:
> On Oct 3, 10:36 pm, Chris Rebert <c...@rebertia.com> wrote:
<snip>

>> Since this sounds like homework, I won't give actual code, but here's
>> a gameplan:
>>
>> 1. Split the list into sublists based on where the runs of zeros stop and start.
>> 2. Categorize the sublists and place them into lists-of-lists based on
>> whether they have nonzero entries.

>> To do the categorization, you'll
>> have to iterate over the original list and track how many previous 0s
>> you've seen consecutively.

Erm, s/categorization/splitting and move this sentence into point #1,
obviously. Mea culpa. :)

Cheers,
Chris

Paul Rubin

unread,
Oct 4, 2009, 1:05:19 AM10/4/09
to
"skor...@gmail.com" <skor...@gmail.com> writes:
> Any suggestions would be appreciated

Look at the docs of the groupby function in the itertools module.

0 new messages