Python | Contiguous Boolean Range
Last Updated :
23 Apr, 2023
Sometimes, we come across a problem in which we have a lot of data in a list in the form of True and False value, this kind of problem is common in Machine learning domain and sometimes we need to know that at a particular position which boolean value was present. Let's discuss certain ways in which this can be done.
Method #1 : Using enumerate() + zip() + list comprehension By using combination of above three functions, this task can easily be accomplished. The enumerate function handles the role of iteration, zip function groups the like values and the logic part is handled by list comprehension.
Python3
# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using enumerate() + zip() + list comprehension
# initializing list
test_list = [True, True, False, False, True,
True, True, True, False, True]
# printing the original list
print ("The original list is : " + str(test_list))
# using enumerate() + zip() + list comprehension
# for Contiguous Boolean Ranging
res = [x for x, (i , j) in enumerate(zip( [2]
+ test_list, test_list + [2])) if i != j]
# printing result
print ("The boolean range list is : " + str(res))
Output:
The original list is : [True, True, False, False, True, True, True, True, False, True] The boolean range list is : [0, 2, 4, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.
Method #2 : Using sum() + accumulate() + groupby() The above three functions can also be clubbed together to achieve the particular task, as they use the iterators to achieve it. The sum function counts each value, groupby groups each one and all together are accumulated by the accumulate function.
Python3
# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using sum() + accumulate() + groupby()
from itertools import accumulate, groupby
# initializing list
test_list = [True, True, False, False, False,
True, True, True, False, False]
# printing the original list
print ("The original list is : " + str(test_list))
# using sum() + accumulate() + groupby()
# for Contiguous Boolean Ranging
res = [0] + list(accumulate(sum(1 for i in j)
for i, j in groupby(test_list)))
# printing result
print ("The boolean range list is : " + str(res))
Output:
The original list is : [True, True, False, False, False, True, True, True, False, False] The boolean range list is : [0, 2, 5, 8, 10]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3 : Using looping
This approach uses a for loop to iterate through the elements in the list and an if statement to check if the current element is different from the previous element. If it is different, the index of the current element is added to the result list.
Here is another approach using a for loop and an if statement:
Python3
# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using for loop and if statement
# initializing list
test_list = [True, True, False, False, False,
True, True, True, False, False]
# printing the original list
print("The original list is:", test_list)
# using for loop and if statement
# for Contiguous Boolean Ranging
res = []
for i, v in enumerate(test_list):
if i == 0 or v != test_list[i-1]:
res.append(i)
res.append(len(test_list))
# printing result
print("The boolean range list is:", res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is: [True, True, False, False, False, True, True, True, False, False]
The boolean range list is: [0, 2, 5, 8, 10]
The resulting list res will contain the starting index of each group of contiguous True or False values in the list. The time complexity of this approach is O(n), where n is the number of elements in the list, and the space complexity is O(n), as it requires a separate result variable for each element in the list.
Method 4 : using the NumPy library.
- Import the NumPy module:
The NumPy module is imported using the "import numpy as np" statement. - Initialize the input list:
The input list containing boolean values is initialized using the "test_list" variable. - Print the original list:
The original list is printed to the console using the "print" statement. - Convert the list to a NumPy array:
The input list is converted to a NumPy array using the "np.array" method and assigned to the "test_arr" variable. - Compute the difference array:
The difference between consecutive elements of the NumPy array is computed using the "np.diff" method after casting the array elements to integer values using "test_arr.astype(int)" and assigned to the "diff_arr" variable. - Compute the indices of the range boundaries:
The indices of the range boundaries are computed using the "np.where" method on the "diff_arr" array to find the indices where the difference is not zero, and then adding 1 to each index to get the upper bound of each range. The resulting array of indices is assigned to the "res" variable. - Add the start and end indices to the result array:
The start index (0) and end index (length of the input array) are added to the "res" array using the "np.insert" and "np.append" methods, respectively. - Print the resulting boolean range list:
The resulting boolean range list is printed to the console using the "print" statement.
Python3
# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using NumPy
# importing NumPy module
import numpy as np
# initializing list
test_list = [True, True, False, False, False,
True, True, True, False, False]
# printing the original list
print("The original list is:", test_list)
# using NumPy for Contiguous Boolean Ranging
test_arr = np.array(test_list)
diff_arr = np.diff(test_arr.astype(int))
res = np.where(diff_arr != 0)[0] + 1
res = np.insert(res, 0, 0)
res = np.append(res, len(test_arr))
# printing result
print("The boolean range list is:", res.tolist())
#This code is contributed by Sujit Mandal
OUTPUT :
The original list is: [True, True, False, False, False, True, True, True, False, False]
The boolean range list is: [0, 2, 5, 8, 10]
Time complexity: O(N), where N is the length of the input list. This is because NumPy operations run in C and are optimized for speed.
Auxiliary space: O(N), where N is the length of the input list. This is because we are creating NumPy arrays of length N.
Similar Reads
Python | Count true booleans in a list
Given a list of booleans, write a Python program to find the count of true booleans in the given list. Examples: Input : [True, False, True, True, False] Output : 3 Input : [False, True, False, True] Output : 2 Method #1: Using List comprehension One simple method to count True booleans in a list i
3 min read
Python - range() for Float Numbers
The range() function in Python is often used to create a sequence of numbers. However by default, it works only with integers. What if we want to use range() with float numbers? Letâs explore how we ca work with range() with float numbers. Using numpy.arange()For a cleaner solution, we can use numpy
2 min read
Python - Extract Missing Ranges
Given list of tuples, start range and end range values, extract the ranges that are missing from the list. Input : test_list = [(7, 2), (15, 19), (38, 50)], strt_val = 5, stop_val = 60 Output : [(5, 7), (2, 60), (2, 15), (19, 60), (19, 38), (50, 60)] Explanation : Missing element ranges starting fro
2 min read
Python - Convert String Truth values to Boolean
Converting string truth values like "True" and "False" into their corresponding boolean values in Python is a straightforward yet useful operation. Methods such as dictionaries, direct comparison, and built-in functions offer simple and efficient ways to achieve this transformation for various use c
2 min read
Python - Test Boolean Value of Dictionary
Sometimes, while working with data, we have a problem in which we need to accept or reject a dictionary on the basis of its true value, i.e all the keys are Boolean true or not. This kind of problem has possible applications in data preprocessing domains. Let's discuss certain ways in which this tas
9 min read
Boolean list initialization - Python
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python.Using List MultiplicationThe most efficient way to initialize a boolean list with identical values i
2 min read
Convert Python boolean values to strings Yes or No
When you're using true or false values in Python, changing them to "Yes" or "No" strings can make your code easier to read. This article shows different ways to do it, giving you choices based on how you like to write your code. Here, we will convert the Python Boolean values to string as Yes or No
3 min read
Python | Ways to convert Boolean values to integer
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task. Convert Boolean values to integers using int()Â Converting bool to an integer using Python typecasting. Python3 # Initialising Values bo
3 min read
Python - Delete elements in range
In Python, we often need to remove elements from a list within a specific range. This can be useful when cleaning data or modifying lists based on certain conditions. Using List Comprehension List comprehension is one of the most Pythonic and efficient ways to filter out elements. It is concise, eas
3 min read
Python - Sort by range inclusion
Given a range, sort tuple Matrix by total range covered in a given range. [Considering tuples which completely lie within range]. Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]], i, j = 2, 15 Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)],
4 min read