Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximum length of consecutive 1’s in a binary string in Python using Map function

  • Difficulty Level : Basic
  • Last Updated : 15 Jul, 2021

We are given a binary string containing 1’s and 0’s. Find the maximum length of consecutive 1’s in it.

Examples: 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input : str = '11000111101010111'
Output : 4

We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The approach is very simple,  

  1. Separate all sub-strings of consecutive 1’s separated by zeros using split() method of string.
  2. Print maximum length of split sub-strings of 1’s.

Python




# Function to find Maximum length of consecutive 1's in a binary string
 
def maxConsecutive1(input):
     # input.split('0') --> splits all sub-strings of consecutive 1's
     # separated by 0's, output will be like ['11','1111','1','1','111']
     # map(len,input.split('0'))  --> map function maps len function on each
     # sub-string of consecutive 1's
     # max() returns maximum element from a list
     print max(map(len,input.split('0')))
 
# Driver program
if __name__ == "__main__":
    input = '11000111101010111'
    maxConsecutive1(input)

Output: 

4

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!