import numpy as np def run_length_encoding(array): repeats = [] current = None counter = 0 for element in array: if element == current: counter += 1 else: if current is not None: repeats.append((current, counter)) current = element counter = 1 repeats.append((current, counter)) values, counts = zip(*repeats) return np.array(values), np.array(counts)
The function run_length_encoding takes an array, flattens and encodes it using run-length encoding, and returns the encoded values and the counts.