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
Python - Contiguous Boolean Range
Given a list of boolean values, we are interested to know the positions where contiguous ranges of the same boolean value start and end. This means finding where a sequence of True values begins and ends, and where a sequence of False values begins and ends.
Using itertools
We can use accumulate along with groupby from the itertools module. The groupby function groups consecutive identical values, and accumulate helps track the cumulative positions where each group ends ?
Example
from itertools import accumulate, groupby
# Given list
bool_values = [False, True, True, False, False]
print("Given list:")
print(bool_values)
# Applying accumulate
positions = [0] + list(accumulate(sum(1 for x in group)
for value, group in groupby(bool_values)))
# Result
print("Positions for range of contiguous values:")
print(positions)
Given list: [False, True, True, False, False] Positions for range of contiguous values: [0, 1, 3, 5]
Using enumerate
The enumerate function along with zip function compares each element with its neighbors. When adjacent elements differ, we mark that position as a boundary between contiguous ranges ?
Example
# Given list
bool_values = [False, True, True, False, False]
print("Given list:")
print(bool_values)
# Using enumerate to find boundaries
positions = [index for index, (prev_val, curr_val) in
enumerate(zip([None] + bool_values, bool_values + [None]))
if prev_val != curr_val]
# Result
print("Positions for range of contiguous values:")
print(positions)
Given list: [False, True, True, False, False] Positions for range of contiguous values: [0, 1, 3, 5]
How It Works
Both methods identify the boundary positions where the boolean value changes. In our example:
- Position 0: Start of first
False - Position 1: Start of
Truesequence - Position 3: Start of second
Falsesequence - Position 5: End of the list
Comparison
| Method | Complexity | Readability |
|---|---|---|
| itertools | O(n) | Moderate |
| enumerate | O(n) | Better |
Conclusion
Both methods effectively find contiguous boolean ranges. The enumerate approach is more readable, while the itertools method demonstrates functional programming concepts. Choose based on your preference for readability versus functional style.
