[Solved] Python: Numpy slicing indepth explnation [closed]


Add a print(N) line after all the N+= lines, and try various Z arrays.

For example

Define a small z with a block of 1s in the middle:

In [29]: z = np.zeros((10,10),int)
In [31]: z[4:6,4:6]=1
In [34]: z[4:8,5]=1

In [35]: z
Out[35]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

pass it to the function:

In [36]: iterate(z)
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  2.  2.  1.  0.  0.  0.]
 [ 0.  0.  0.  2.  3.  3.  2.  0.  0.  0.]
 [ 0.  0.  0.  2.  4.  4.  3.  0.  0.  0.]
 [ 0.  0.  0.  1.  4.  3.  3.  0.  0.  0.]
 [ 0.  0.  0.  0.  2.  1.  2.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  1.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

N has counted the number of neighbors that are 1. Check the counts yourself.

Out[36]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

Try various patterns, repeat the iterate and watch the pattern change. Some die away, some move in an order fashion, some ‘blink’, etc.

In a line like:

N[1:, 1:] += Z[:-1, :-1]

the RHS is an upper left portion (here 9×9); LHS is a bottom right, again 9×9. There are 8 N+= expressions, calculating the 8 neighbors (in a 3×3 block, minus the center). With this offset slicing it can do the count for all points in Z at once.

For a start, a 1 row array might be easier to visualize

In [47]: z = np.zeros((1,10),int)
In [49]: z[0,4:7]=1
In [50]: z
Out[50]: array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0]])
In [51]: iterate(z)
[[ 0.  0.  0.  1.  1.  2.  1.  1.  0.  0.]]
Out[51]: array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])

I think this works best if all the edge values of z are 0.

This array creates the glider that is animated on https://en.wikipedia.org/wiki/Glider_(Conway%27s_Life)

In [64]: z = np.zeros((10,10),int)
In [65]: z[1,2]=1;z[2,3]=1;z[3,1:4]=1

solved Python: Numpy slicing indepth explnation [closed]