Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum length of consecutive 1's in a binary string in Python using Map function
When working with binary strings, you may need to find the maximum length of consecutive 1's. Python provides several approaches using built-in functions like split() with map() and regular expressions.
Using Split and Map
The split() function divides a string by a delimiter. When we split by '0', we get segments of consecutive 1's. The map() function applies len() to each segment, and max() finds the longest one ?
Example
data = '11110000111110000011111010101010101011111111'
def max_consecutive_ones(binary_string):
return max(map(len, binary_string.split('0')))
result = max_consecutive_ones(data)
print("Maximum Number of consecutive one's:", result)
The output of the above code is ?
Maximum Number of consecutive one's: 8
Using Regular Expression
The re module can find patterns of consecutive 1's using the pattern 1+ (one or more 1's). We then find the maximum length among all matches ?
Example
import re
data = '11110000111110010011'
# Find all blocks of consecutive 1's
ones_blocks = re.findall(r"1+", data)
print("The blocks of one's:", ones_blocks)
# Find maximum length
max_length = len(max(ones_blocks, key=len))
print("Maximum Number of consecutive one's =", max_length)
The output of the above code is ?
The blocks of one's: ['1111', '11111', '1', '11'] Maximum Number of consecutive one's = 5
Comparison
| Method | Complexity | Best For |
|---|---|---|
split() + map()
|
O(n) | Simple binary strings |
| Regular Expression | O(n) | Complex pattern matching |
Conclusion
Use split() with map() for simple cases where you only need the maximum count. Use regular expressions when you need more detailed pattern analysis or want to extract all consecutive blocks.
