rougier / numpy-100

100 numpy exercises (with solutions)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Alternative solution for 66

Fisher-Wang opened this issue · comments

w, h = 16, 16
img = np.random.randint(0, 256, (w, h, 3)).astype(np.ubyte)
colors = np.unique(img.reshape(-1, 3), axis=0)
n = len(colors) 
print(n)

Can you give some context (and difference with proposed solution)?

Sure. In order to compare the colors, the proposed solution encode them as an integer with radix 256, which is not necessary. Instead, we can directly compare the colors, by specifying the axis, and that's what line 3 does. Note that this approach work only when the array is 2D, so just reshape it in advance.

Makes sense. Can you make a PR adding your alternative while keeping the old way (which has been modified by #142 but doesn't yet show up on the generator file)