Last active
February 2, 2016 21:18
-
-
Save dela3499/322fb8d059ac83fb338e to your computer and use it in GitHub Desktop.
Generate a checkered matrix in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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