Skip to content

Instantly share code, notes, and snippets.

@dela3499
Last active February 2, 2016 21:18
Show Gist options
  • Save dela3499/322fb8d059ac83fb338e to your computer and use it in GitHub Desktop.
Save dela3499/322fb8d059ac83fb338e to your computer and use it in GitHub Desktop.
Generate a checkered matrix in Python.
from itertools as it
# Generator a -> Int -> List a
def take(generator, n):
""" Return first n elements of generator as list. """
return list(it.islice(generator, n))
# List a -> Int -> List a
def takecycle(elements, n):
""" Return first n elements of infinite cycle given by elements. """
return thread_first(
elements,
it.cycle,
(take, n))
# Int -> Int -> 2D Array Int
def checker(rows, cols):
""" Produce a checkerboard matrix of zeros and ones of given shape. """
first_row = np.array(takecycle([False,True], cols))
return np.array(takecycle([first_row, ~first_row], rows)).astype(int)
assert checker(2,3) = \
[[0,1,0],
[1,0,1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment