generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated.

import numpy as np def encode(a): a = np.array(a) b = np.array(np.diff(a)) c = np.zeros(len(a)) c[0] = a[0] if(len(a)==1): return [a[0]], [1] else: for i in range(len(a)-1): if b[i] == 0: c[i+1] = 0 else: c[i+1] = a[i+1] d = np.unique(c, return_counts=True) return d[0], d[1] print(encode([1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2]))

Questions about programming?Chat with your personal AI assistant