Numpy Exercise 1

Imports


In [1]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns

In [2]:
import antipackage
import github.ellisonbg.misc.vizarray as va


Downloading:  https://raw.githubusercontent.com/ellisonbg/misc/master/vizarray.py
Using existing version:  github.ellisonbg.misc.vizarray

Checkerboard

Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0:

  • Your function should work for both odd and even size.
  • The 0,0 element should be 1.0.
  • The dtype should be float.

In [3]:
va.enable()

In [41]:
def checkerboard(size):
    k = np.zeros((size,size))
    for i in range(size):
        if size %2 == 0:
            k[i,i%2:size:2] = 1.0
        elif size %2 == 1:
            k[i,i%2:size+1:2] = 1.0
    return k

print checkerboard(4)


[[ 1.  0.  1.  0.]
 [ 0.  1.  0.  1.]
 [ 1.  0.  1.  0.]
 [ 0.  1.  0.  1.]]

In [42]:
va.vizarray(checkerboard(5))


Out[42]:

In [43]:
a = checkerboard(4)
assert a[0,0]==1.0
assert a.sum()==8.0
assert a.dtype==np.dtype(float)
assert np.all(a[0,0:5:2]==1.0)
assert np.all(a[1,0:5:2]==0.0)

b = checkerboard(5)
assert b[0,0]==1.0
assert b.sum()==13.0
assert np.all(b.ravel()[0:26:2]==1.0)
assert np.all(b.ravel()[1:25:2]==0.0)

Use vizarray to visualize a checkerboard of size=20 with a block size of 10px.


In [45]:
# YOUR CODE HERE
# raise NotImplementedError()
m = checkerboard(20)
va.set_block_size(10)
va.vizarray(m)


Out[45]:

In [46]:
assert True

Use vizarray to visualize a checkerboard of size=27 with a block size of 5px.


In [47]:
# YOUR CODE HERE
# raise NotImplementedError()
r = checkerboard(27)
va.set_block_size(5)
va.vizarray(r)


Out[47]:

In [48]:
assert True

In [49]:
def checkerboard(w, h) :
    re = np.r_[ w*[0,1] ]
    ro = np.r_[ w*[1,0] ]
    return np.row_stack(h*(re, ro))


AB = checkerboard(5, 10)

In [50]:
va.enable()

In [51]:
def gen_checkerboard(size):
    even = 1 * [0,1]
    odd = 1* [1,0]
    checkerboard = np.row_stack(size/2*(even, odd))
    return checkerboard.repeat(size, axis = 0)
print (gen_checkerboard(2))


[[0 1]
 [0 1]
 [1 0]
 [1 0]]

In [ ]: