Maciej
Maciej

Reputation: 133

How to count in a row results from text file

i would like to know how to count in a row results from text file. I wroted this code:

from itertools import groupby

def count_runs_of(seq, val):
    return sum(key == val for key, group in groupby(seq))

Example:

>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
1
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
2
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3, 9, 2, 4, 3, 3, 3], 3)
3
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 2)
2

I want to know how long serie it is. For example, when i have "1" in first result, i want to also print "3" (because there was 3 x 3 in a row). Could You help me? Thank You

Upvotes: 1

Views: 61

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

You were pretty close, you get get the length of a group by looping on it using sum() and generator expression. This will return length of all such runs in the list:

>>> def count_runs_of(seq, val):
    return [sum(1 for _ in g) for k, g in groupby(seq) if k == val]
... 
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4], 3)
[3]
>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 118011

def count_runs_of(seq, val):
    return [len(list(group)) for key, group in groupby(seq) if key == val]

Example

>>> count_runs_of([1, 2, 3, 3, 3, 1, 2, 2, 4, 3, 3], 3)
[3, 2]

Upvotes: 2

Related Questions