How can I convert this code into one liner or reduce the number of lines using list comprehension?

def consecutive_zeros(input_binary):
  count = 0
  count_list = list()
  for x in input_binary:
    if x == "0":
        count += 1
    else:
        count_list.append(count)
        count = 0
  return max(count_list)

I tried different ways to implement the same but was getting syntax error or wrong output. Is there a more efficient way in which I can implement the same? How to make it one liner?


It looks like you want to find the longest sequence of zeros following a one. If this is correct zeros in the end should not be counted. I have a solution that is based on string operations as I assume your input is a string. If not please consider adding an example input to your question.

def consecutive_zeros(input_binary):
    return max(map(len, input_binary.rstrip('0').split('1')))
    
print(consecutive_zeros('0000111110001000000')) # 4
print(consecutive_zeros('00001111100010000001')) # 6

EDIT: As your function is named consecutive_zeros it could be that you also want a sequence in the end, which would not be counted in your code. If you want to count it you can use this code:

def consecutive_zeros(input_binary):
    return max(map(len, input_binary.split('1')))
    
print(consecutive_zeros('0000111110001000000')) # 6
print(consecutive_zeros('00001111100010000001')) # 6