msampaio
msampaio

Reputation: 3433

How to count sequences of repeated numbers in Python sequences?

I want to count how many times small sequences of adjacent repeated number different from zero occurs in a given sequence. Let three sequences:

seq1 = [1, 1, 2, 2, 3, 3, 3]
seq2 = [1, 1, 0, 1, 1]
seq3 = [1, 1, 0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 0, 0, 0]

The sequence seq1 has 3 small sequences: [1, 1], [2, 2], and [3, 3, 3]; the sequence seq2 has 2 small sequences, both [1, 1] separated by 0; and the sequence seq3, has 4 small sequences: the first [1, 1], [1, 1, 1], [2, 2], and the second [1, 1].

Upvotes: 3

Views: 2378

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250991

Use itertools.groupby:

>>> from itertools import groupby
for k,g in groupby(seq1):
    if k != 0:
        print list(g)
...         
[1, 1]
[2, 2]
[3, 3, 3]

for k,g in groupby(seq2):
    if k != 0:
        print list(g)
...         
[1, 1]
[1, 1]

I think you can do the counting now. :)

Upvotes: 5

Related Questions