Numpy Exercise 1

Imports


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

In [3]:
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 [7]:
def checkerboard(size):    #I couldn't figure this out on my own. My partner helped me during pair-programming, as a result are codes are pretty much exactly alike, but I understand now how it works.
    """Return a 2d checkboard of 0.0 and 1.0 as a NumPy array"""
    # YOUR CODE HERE   (Late Assignment)
    f = np.empty((size, size), dtype=np.float)  #Creates NxN empty matrix
    for i in range(size):
            for j in range(size):
                if (i+j)%2 == 0:                #Goes element wise to see if the sum of the element components is\
                    f[i, j] = 1                 #even or odd. If odd, it's given a value of 0, if even, 1.
                else:
                    f[i, j]=0
    return f
print checkerboard(10)                         #prints NxN matrix board


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

In [8]:
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 [10]:
# YOUR CODE HERE
va.set_block_size(10)
va.vizarray(checkerboard(20))


Out[10]:

In [11]:
assert True

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


In [12]:
# YOUR CODE HERE
va.set_block_size(5)
va.vizarray(checkerboard(27))


Out[12]:

In [13]:
assert True

In [ ]: