w3resource

Python: Find maximum length of consecutive 0’s in a given binary string


Find max length of consecutive zeros (binary).

Write a Python program to find the maximum length of consecutive 0's in a given binary string.

Visual Presentation:

Python String: Find maximum length of consecutive 0’s in a given binary string.

Sample Solution:

Python Code:

# Define max_consecutive_0 function 
def max_consecutive_0(input_str):

# Split string on '1' and map length of each substring  
# Returns max length of 0's
   return max(map(len,input_str.split('1'))) 

# Test string  
str1 = '111000010000110'

# Print original string 
print("Original string:" + str1)  

# Print max consecutive 0's
print("Maximum length of consecutive 0’s:")
print(max_consecutive_0(str1))

# Another test string
str1 = '111000111' 

# Print original string
print("Original string:" + str1)

# Print max consecutive 0's  
print("Maximum length of consecutive 0’s:")
print(max_consecutive_0(str1)) 

Sample Output:

Original string:111000010000110
Maximum length of consecutive 0’s:
4
Original string:111000111
Maximum length of consecutive 0’s:
3

Flowchart:

Flowchart: Find maximum length of consecutive 0’s in a given binary string

For more Practice: Solve these Related Problems:

  • Write a Python program to scan a binary string and determine the maximum number of consecutive '0's using a loop.
  • Write a Python program to use regular expressions to find all sequences of '0's and return the length of the longest sequence.
  • Write a Python program to implement a function that iterates over a binary string and tracks the current and maximum counts of consecutive zeros.
  • Write a Python program to use itertools.groupby to group consecutive zeros and then compute the maximum group length.

Go to:


Previous: Write a Python program to remove leading zeros from an IP address.
Next: Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no common letters print “No common characters”.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.