Open In App

Python | Contiguous Boolean Range

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


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]

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. 

  1. Import the NumPy module:
    The NumPy module is imported using the “import numpy as np” statement.
  2. Initialize the input list:
    The input list containing boolean values is initialized using the “test_list” variable.
  3. Print the original list:
    The original list is printed to the console using the “print” statement.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads