Jupyter Snippet CB2nd 01_blocks
Jupyter Snippet CB2nd 01_blocks
3.1. Teaching programming in the Notebook with IPython blocks
import time
from IPython.display import clear_output
from ipythonblocks import BlockGrid, colors
grid = BlockGrid(width=5, height=5,
fill=colors['Purple'])
grid.show()
grid[0, 0] = colors['Lime']
grid[-1, 0] = colors['Lime']
grid[:, -1] = colors['Lime']
grid.show()
n = 5
grid = BlockGrid(width=2 * n + 1,
height=2 * n + 1,
fill=colors['White'])
A = grid[n + 1:, :n]
B = grid[:n, n + 1:]
C = grid[n + 1:, n + 1:]
A[:, :] = colors['Cyan']
B[:, :] = colors['Lime']
C[:, :] = colors['Yellow']
grid.show()
for i in range(n):
for j in range(n):
# We reset the matrix colors.
A[:, :] = colors['Cyan']
B[:, :] = colors['Lime']
C[:, :] = colors['Yellow']
# We highlight the adequate rows
# and columns in red.
A[i, :] = colors['Red']
B[:, j] = colors['Red']
C[i, j] = colors['Red']
# We animate the grid in the loop.
clear_output()
grid.show()
time.sleep(.25)
# We downsample the image by a factor of 4 for
# performance reasons.
img = plt.imread('https://github.com/ipython-books/'
'cookbook-2nd-data/blob/master/'
'beach.png?raw=true')[::4, ::4, :]
rgb = [img[..., i].ravel() for i in range(3)]
height, width = img.shape[:2]
grid = BlockGrid(width=width, height=height,
block_size=2, lines_on=False)
for block, r, g, b in zip(grid, *rgb):
block.rgb = (r * 255, g * 255, b * 255)
grid.show()