Skip to content

Instantly share code, notes, and snippets.

@maulikmadhavi
Created August 27, 2024 23:00
Show Gist options
  • Select an option

  • Save maulikmadhavi/2e60f79f2d9ede529401eea9e100cab6 to your computer and use it in GitHub Desktop.

Select an option

Save maulikmadhavi/2e60f79f2d9ede529401eea9e100cab6 to your computer and use it in GitHub Desktop.
import numpy as np
def majority_count_sliding_window(binary_vector, window_size=5):
"""
Applies a sliding window to the binary vector and sets the output to 1 if the majority
of the elements in the window are 1s.
Parameters:
binary_vector (np.array): The input binary vector.
window_size (int): The size of the sliding window.
Returns:
np.array: The output binary vector after applying the majority count sliding window.
"""
# Pad the input array with 2 zeros on each side
padded_vector = np.pad(binary_vector, (2, 2), 'constant', constant_values=0)
# Initialize the output array
output = np.zeros_like(binary_vector)
# Iterate through the original array indices
for i in range(len(binary_vector)):
# Get the window from the padded array
window = padded_vector[i:i+window_size]
# Count the number of 1s in the window
count = np.sum(window)
# Check if the count is greater than half the window size
if count > window_size // 2:
output[i] = 1
return output
# Example usage
binary_vector = np.array([0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
result = majority_count_sliding_window(binary_vector)
print(result)
print(len(binary_vector), len(result))
def start_end_detect(result: list):
"""
Detects the start and end indices of contiguous groups of 1s in the binary vector.
Parameters:
result (list): The input binary vector.
Returns:
list: A list of tuples where each tuple contains the start and end indices of a group of 1s.
"""
start_end_pairs = []
start = None
for i in range(len(result)):
if i == 0:
if result[i] == 1:
start = i
elif result[i] == 1 and result[i-1] == 0:
start = i
elif result[i] == 0 and result[i-1] == 1 and start is not None:
start_end_pairs.append((start, i-1))
start = None
# If the last element is 1, close the last group
if start is not None:
start_end_pairs.append((start, len(result)-1))
return start_end_pairs
print(start_end_detect(result.tolist()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment