rougier / numpy-100

100 numpy exercises (with solutions)
MIT License
12.17k stars 5.74k forks source link

About question 19 #191

Open hacshyac opened 1 year ago

hacshyac commented 1 year ago

the alternative solution does not work for creating a checkerboard pattern.

# Alternative solution: Using reshaping
arr = np.ones(64,dtype=int)
arr[::2]=0
arr = arr.reshape((8,8))
print(arr)

this will be the output. [[0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1]]

But what we want is

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)

[[0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0]]

or

z = np.zeros((8, 8), int)
z[1::2, 1::2] = 1
z[::2, ::2] = 1
print(z)

[[1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1]]

rougier commented 1 year ago

Thanks, it has been fixed recently.