NISHIO Hirokazu[Translate]
番兵付きの一次元配列

改行限り文字列を番兵付きの一次元配列にする。
python
C = np.zeros((H + 2, W + 2), np.bool_) C[1:-1, 1:-1] = np.frombuffer(read(), 'S1').reshape(H, -1)[:, :W] == b'.' C = C.ravel() H += 2 W += 2

ValueError: could not broadcast input array from shape (3,0) into shape (3,5)
already read all data from stdin

各ステップ解説
python
>>> np.frombuffer(b"...\n.@.\n...\n", "S1") array([b'.', b'.', b'.', b'\n', b'.', b'@', b'.', b'\n', b'.', b'.', b'.', b'\n'], dtype='|S1') >>> _.reshape(3, -1) array([[b'.', b'.', b'.', b'\n'], [b'.', b'@', b'.', b'\n'], [b'.', b'.', b'.', b'\n']], dtype='|S1') >>> _[:,:3] array([[b'.', b'.', b'.'], [b'.', b'@', b'.'], [b'.', b'.', b'.']], dtype='|S1') >>> _ == b"." array([[ True, True, True], [ True, False, True], [ True, True, True]]) >>> C = np.zeros((3 + 2, 3 + 2), np.bool_) >>> C[1:-1, 1:-1] = _ >>> C array([[False, False, False, False, False], [False, True, True, True, False], [False, True, False, True, False], [False, True, True, True, False], [False, False, False, False, False]]) >>> C.ravel() array([False, False, False, False, False, False, True, True, True, False, False, True, False, True, False, False, True, True, True, False, False, False, False, False, False])

"Engineer's way of creating knowledge" the English version of my book is now available on [Engineer's way of creating knowledge]

(C)NISHIO Hirokazu / Converted from [Scrapbox] at [Edit]