rougier/numpy-100

An alternative solution for Q.70

iamyifan opened this issue · 2 comments

  1. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
    hint: array[::4]
# Author: Warren Weckesser

Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)

A more readable function from numpy: numpy.insert(arr, obj, values, axis=None). NumPy Doc

Thus, an alternative solution will be:

Z = np.array([1, 2, 3, 4, 5])
Z0 = np.insert(a[..., np.newaxis], [1], [[0, 0, 0] for  _ in range(len(a))], axis=1)
Z0 = Z0.flatten()[:-3]
print(Z0)

@Jeff1999 Thansk. Did you time the two solutions ? I'm not too confident with the for loop and a big array.