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


Sometimes when dealing with the binary representation of numbers we may be needed to find out how many continuous 1’s are present in the number. This article shows two ways how we can find out that.

Using Split and Map

The split function in python can be used to split the given string into multiple strings. We split it by zeros and the map function is used to find the maximum length among the splits generated.

Example

 Live Demo

data = '11110000111110000011111010101010101011111111'
def Max_len_cons_1(data):
print ("Maximum Number of consecutive one's: ",max(map(len,data.split('0'))) )
Max_len_cons_1(data)

Output

Running the above code gives us the following result −

Maximum Number of consecutive one's: 8

Using regular expression

The re module in python can also be used to count the maximum number of consecutive 1’s. Here we find the pattern of 1+ which indicates one or more number of 1’s present. Then find the maximum length among those pattern.

Example

 Live Demo

data = '11110000111110010011'
import re
the_ones = re.findall(r"1+", data)
print("The blocks of one's: ",the_ones)
print("Maximum Number of consecutive one's =", len(max(the_ones, key=len)))

Output

Running the above code gives us the following result −

The blocks of one's: ['1111', '11111', '1', '11']
Maximum Number of consecutive one's = 5
raja
Published on 04-Feb-2020 06:38:27
Advertisements