Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An alternative solution for Q.70 #160

Open
iamyifan opened this issue Dec 9, 2021 · 2 comments
Open

An alternative solution for Q.70 #160

iamyifan opened this issue Dec 9, 2021 · 2 comments

Comments

@iamyifan
Copy link
Contributor

iamyifan commented Dec 9, 2021

  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)
@heyzwming
Copy link

heyzwming commented Dec 9, 2021 via email

@rougier
Copy link
Owner

rougier commented Dec 15, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants