numpy-100 icon indicating copy to clipboard operation
numpy-100 copied to clipboard

An alternative solution for Q.70

Open iamyifan opened this issue 2 years ago • 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)

iamyifan avatar Dec 09 '21 02:12 iamyifan

您好,您的邮件我已收到,我会尽快回复您。

heyzwming avatar Dec 09 '21 02:12 heyzwming

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

rougier avatar Dec 15 '21 12:12 rougier