rougier/numpy-100

Alternative solution for 87.

FirefoxMetzger opened this issue · 5 comments

Numpy has (finally) "upstreamed" skimage's view_as_windows under the name sliding_window_view. With this we can write exercise 87 using more verbose clear syntax

Z = np.ones((16,16))
k = 4

windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
relevant_windows = windows[::k, ::k, ...]
S = np.sum(np.sum(relevant_windows, axis=-1), axis=-1)

or if we prefer (potentially hard to maintain) one-liners

Z = np.ones((16,16))
k = 4

S = np.sum(
    np.sum(
        np.lib.stride_tricks.sliding_window_view(Z, (k, k))[::k, ::k, ...]
        axis=-1), 
    axis=-1)

I'm not a big fan of this syntax,windows and relevant_windows are quite redundant.

Sure, we can also write

Z = np.ones((16,16))
k = 4

windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = np.sum(np.sum(windows[::k, ::k, ...], axis=-1), axis=-1)

The main point is that there is an alternative solution. Do you think it is worthwhile to add it here? If so, we can discuss how to best formulate it and I can submit a PR.

If you don't like the double sum, there is of course

S = windows[::k, ::k].reshape(*(x//k for x in Z.shape), -1).sum(-1)

Sorry for the delay and yes, it's worth a PR to show the alternative. Can you do it?

@rougier sure. This should do the trick.