

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
- Related Questions & Answers
- Count Binary String without Consecutive 1's
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- Python program using map function to find row with maximum number of 1's
- Python program using the map function to find a row with the maximum number of 1's
- Python map function to find the row with the maximum number of 1’s
- Maximum Consecutive Increasing Path Length in Binary Tree in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Count number of binary strings without consecutive 1's in C
- Maximum length of segments of 0’s and 1’s in C++
- Maximum Consecutive Zeroes in Concatenated Binary String in C++
- Python program to check if there are K consecutive 1’s in a binary number?
- Program to find length of longest consecutive path of a binary tree in python
- Maximum consecutive one’s (or zeros) in a binary circular array in C++
Advertisements