Numpy Exercise 1

Imports


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

In [26]:
import antipackage
import github.ellisonbg.misc.vizarray as va
va.enable()

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 [37]:
def checkerboard(size):
    """Return a 2d checkboard of 0.0 and 1.0 as a NumPy array"""
    #Creates a size x size array of zeros
    a = np.zeros((size,size), dtype = np.float)
    
    
    #iterates through every row and every other col in the array 
    for col in range(0,size,2):
        for row in range(0,size,1):
            
            
            if size % 2 == 0:
                a[row,col-row] = 1.0
            #This else statement does not work correctly but it is the odd size bug fix. 
            else:
                a[row-col,row] = 1.0
           

    
    return (a)


Out[37]:

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)


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-43-4aa63174c227> in <module>()
      8 b = checkerboard(5)
      9 assert b[0,0]==1.0
---> 10 assert b.sum()==13.0
     11 assert np.all(b.ravel()[0:26:2]==1.0)
     12 assert np.all(b.ravel()[1:25:2]==0.0)

AssertionError: 

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


In [40]:
#Set the block size to 10 pixels and then print the vizarray
va.set_block_size(10)
va.vizarray(checkerboard(20))


Out[40]:

In [ ]:
assert True

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


In [42]:
#Set the block size to 5 pixels and then print the vizarray
va.set_block_size(5)
va.vizarray(checkerboard(27))


Out[42]:

In [ ]:
assert True