0

My code currently returns a row of a CSV file with print(line):

['0', '0', '0', '0', '0', '0', '0', '0', '1', '0', 'B']

I'd like to count the consecutive instances of zero giving me the largest amount of free space in a single block for that row (seat booking system project). I'd also like to count the amount of zeroes giving me two values - the largest block of zeroes and the total amount of zeroes in the list. Any help is much appreciated!

1
  • Can the strings be longer than 1 symbol? Commented Mar 12, 2014 at 13:34

2 Answers 2

4

Using itertools.groupby() to group by runs of zeros:

from itertools import groupby

max_run = 0
totalcount = line.count('0')
if totalcount:
    max_run = max(sum(1 for _ in g) for k, g in groupby(line) if k == '0')

The if is needed because if there are no '0' values in the line, max() throws an exception complaining about an empty sequence.

Demo:

>>> from itertools import groupby
>>> line = ['0', '0', '0', '0', '0', '0', '0', '0', '1', '0', 'B']
>>> line.count('0')
9
>>> max(sum(1 for _ in g) for k, g in groupby(line) if k == '0')
8
Sign up to request clarification or add additional context in comments.

Comments

3
>>> from itertools import groupby
>>> lis = ['0', '0', '0', '0', '0', '0', '0', '0', '1', '0', 'B']

Total count:

>>> lis.count('0')
9

Max consecutive zeroes:

>>> max(sum(1 for _ in g) for k, g in groupby(lis) if k=='0')
8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.