Solutions

Different arrays

  • We will make each array one dimensional, with three values for arange, linspace and ones:
    np.arange(3)
    np.linspace(0,1,3)
    np.ones(3)
    
  • We will make each array two dimensional, with three values in each dimension for zeros, eye and diag:
    np.zeros((3,3))
    np.eye(3)
    np.diag(np.arange(1,4))
    
  • We will make each array one dimensional, with three values for random.rand (uniform random numbers) and random.randn (Gaussian):
    np.random.rand(3)
    np.random.randn(3)
    
  • np.empty creates an array of given size eg: np.empty(3) with uninitialised memory (seemingly random values). This is NOT useful and can cause errors if these uninitialised values are used accidentally in a calculation. If you wish to allocate a NumPy array, but not set numerical values, you might use np.ones(3)*np.nan to fill an appropriately sized array with np.nan the not a number value. This will now cause errors if the value is not set correctly, or at least be obvious if it is used in a calculation. See NaN for detailed information.

Notice if you put all these in the same cell you only see the last array, you can either put each array in its own cell, or print each one individually.

An array puzzle

One solution using 4 founction calls is:

np.arange(10,101,10).reshape(2,5).transpose().flatten()

A one line solution which only uses one function call is:

np.array([10,  60,  20,  70,  30,  80,  40,  90,  50, 100])

Although not in the spirit of the puzzle exercise, it if far easier to see what is happening for this small array. Of course for larger arrays this would be impractical.