Skip to content

100 narray exercises

Masahiro TANAKA edited this page Jul 15, 2016 · 40 revisions

This is narray version of 100 numpy exercises (Repository)

  1. Import the numpy package under the name np (★☆☆)

    Python:

import numpy as np


    Ruby:
    ```ruby
require "numo/narray"
  1. Print the numpy version and the configuration (★☆☆)

    Python:

print(np.version) np.show_config()


    Ruby:
    ```ruby
p Numo::NArray::VERSION
  1. Create a null vector of size 10 (★☆☆)

    Python:

Z = np.zeros(10) print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.zeros(10)
p z
  1. How to get the documentation of the numpy add function from the command line ? (★☆☆)

    Python:

python -c "import numpy; numpy.info(numpy.add)"


    Ruby:
    ```bash
ri 'Numo::DFloat#+'
  1. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

    Python:

Z = np.zeros(10) Z[4] = 1 print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.zeros(10)
z[4] = 1
p z
  1. Create a vector with values ranging from 10 to 49 (★☆☆)

    Python:

Z = np.arange(10,50) print(Z)


    Ruby:
    ```ruby
z = Numo::Int32[10..49]
p z
  1. Reverse a vector (first element becomes last) (★☆☆)

    Python:

Z = np.arange(50) Z = Z[::-1]


    Ruby:
    ```ruby
z = Numo::Int32.new(50).seq
z = z.reverse
  1. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

    Python:

Z = np.arange(9).reshape(3,3) print(Z)


    Ruby:
    ```ruby
z = Numo::Int32.new(3,3).seq
p z
  1. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

    Python:

nz = np.nonzero([1,2,0,0,4,0]) print(nz)


    Ruby:
    ```ruby
nz = Numo::NArray[1,2,0,0,4,0].ne(0).where
p nz
  1. Create a 3x3 identity matrix (★☆☆)

    Python:

Z = np.eye(3) print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.eye(3)
p z
  1. Create a 3x3x3 array with random values (★☆☆)

    Python:

Z = np.random.random((3,3,3)) print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.new(3,3,3).rand
p z
  1. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

    Python:

Z = np.random.random((10,10)) Zmin, Zmax = Z.min(), Z.max() print(Zmin, Zmax)


    Ruby:
    ```ruby
z = Numo::DFloat.new(3,3,3).rand
zmin, zmax = z.minmax
p zmin, zmax
  1. Create a random vector of size 30 and find the mean value (★☆☆)

    Python:

Z = np.random.random(30) m = Z.mean() print(m)


    Ruby:
    ```ruby
z = Numo::DFloat.new(30).rand
m = z.mean
p m
  1. Create a 2d array with 1 on the border and 0 inside (★☆☆)

    Python:

Z = np.ones((10,10)) Z[1:-1,1:-1] = 0


    Ruby:
    ```ruby
z = Numo::DFloat.ones(10,10)
z[1..-2,1..-2] = 0
  1. What is the result of the following expression ? (★☆☆)

    Python:

0 * np.nan np.nan == np.nan np.inf > np.nan np.nan - np.nan 0.3 == 3 * 0.1


    Ruby:
    ```ruby
0 * Float::NAN
Float::NAN == Float::NAN
Float::INFINITY > Float::NAN
Float::NAN - Float::NAN
0.3 == 3 * 0.1
  1. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

    Python:

Z = np.diag(1+np.arange(4),k=-1) print(Z)


    Ruby:
    ```ruby
z = Numo::Int32.zeros(5,5)
z.diagonal(-1)[] = Numo::Int32[1..4]
p z
  1. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)

    Python:

Z = np.zeros((8,8),dtype=int) Z[1::2,::2] = 1 Z[::2,1::2] = 1 print(Z)


    Ruby:
    ```ruby
x = Numo::Int32.new(1,8).seq
y = Numo::Int32.new(8,1).seq
z = (x+y)%2
p z
  1. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element ?

    Python:

print(np.unravel_index(100,(6,7,8)))


    Ruby:
    ```ruby
# NArray allows unraveled index access
z = Numo::Int32.new(6,7,8).seq
p z[100]
  1. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

    Python:

Z = np.tile( np.array(0,1],[1,0), (4,4)) print(Z)


    Ruby:
    ```ruby
# todo
  1. Normalize a 5x5 random matrix (★☆☆)

    Python:

Z = np.random.random((5,5)) Zmax, Zmin = Z.max(), Z.min() Z = (Z - Zmin)/(Zmax - Zmin) print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.new(5,5).rand
zmin, zmax = z.minmax
z = (z - zmin)/(zmax - zmin)
p z
  1. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)

    Python:

Z = np.dot(np.ones((5,3)), np.ones((3,2))) print(Z)


    Ruby:
    ```ruby
x = Numo::DFloat.ones(5,3)
y = Numo::DFloat.ones(3,2)
z = x.dot y
p z
  1. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

    Python:

Author: Evgeni Burovski

Z = np.arange(11) Z[(3 < Z) & (Z <= 8)] *= -1


    Ruby:
    ```ruby
z = Numo::Int32.new(11).seq
z[(3 < z) & (z <= 8)] *= -1
  1. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

    Python:

Z = np.zeros((5,5)) Z += np.arange(5) print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.zeros(5,5)
z += Numo::Int32.new(5).seq
p z
  1. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

Python: ```python def generate(): for x in xrange(10): yield x Z = np.fromiter(generate(),dtype=float,count=-1) print(Z)


    Ruby:
    ```ruby
# no generator in ruby
  1. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

    Python:

Z = np.linspace(0,1,12,endpoint=True)[1:-1] print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.linspace(0,1,12)[1..-2]
p z
  1. Create a random vector of size 10 and sort it (★★☆)

    Python:

Z = np.random.random(10) Z.sort() print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.new(10).rand
z = z.sort
p z
  1. How to sum a small array faster than np.sum ? (★★☆)

    Python:

Author: Evgeni Burovski

Z = np.arange(10) np.add.reduce(Z)


    Ruby:
    ```ruby
z = Numo::Int32.new(10).seq
z.sum
  1. Consider two random array A anb B, check if they are equal (★★☆)

    Python:

A = np.random.randint(0,2,5) B = np.random.randint(0,2,5) equal = np.allclose(A,B) print(equal)


    Ruby:
    ```ruby
# todo
  1. Make an array immutable (read-only) (★★☆)

    Python:

Z = np.zeros(10) Z.flags.writeable = False Z[0] = 1


    Ruby:
    ```ruby
z = Numo::DFloat.zeros(10)
z.freeze
z[0] = 1
  1. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

    Python:

Z = np.random.random((10,2)) X,Y = Z[:,0], Z[:,1] R = np.sqrt(X2+Y2) T = np.arctan2(Y,X) print(R) print(T)


    Ruby:
    ```ruby
z = Numo::DFloat.new(10,2).rand
x,y = z[true,0], z[true,1]
r = Numo::NMath.sqrt(x**2+y**2)
t = Numo::NMath.atan2(y,x)
p r
p t
  1. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

    Python:

Z = np.random.random(10) Z[Z.argmax()] = 0 print(Z)


    Ruby:
    ```ruby
z = Numo::DFloat.new(10).rand
z[z.max_index] = 0
p z
  1. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)

    Python:

Z = np.zeros((10,10), [('x',float),('y',float)]) Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10), np.linspace(0,1,10)) print(Z)


    Ruby:
    ```ruby
  1. Given two arrays, X and Y, construct the Cauchy matrix C (Cij = 1/(xi - yj))

    Python:

Author: Evgeni Burovski

X = np.arange(8) Y = X + 0.5 C = 1.0 / np.subtract.outer(X, Y) print(np.linalg.det(C))


    Ruby:
    ```ruby
# todo
  1. Print the minimum and maximum representable value for each numpy scalar type (★★☆)

    Python:

    for dtype in [np.int8, np.int32, np.int64]:
       print(np.iinfo(dtype).min)
       print(np.iinfo(dtype).max)
    for dtype in [np.float32, np.float64]:
       print(np.finfo(dtype).min)
       print(np.finfo(dtype).max)
       print(np.finfo(dtype).eps)

    Ruby:

todo


1. How to print all the values of an array ?  (★★☆)

    Python:
    ```python
np.set_printoptions(threshold=np.nan)
Z = np.zeros((25,25))
print(Z)
Ruby:
```ruby

Numo::NArray.inspect_cols = nil Numo::NArray.inspect_rows = nil z = Numo::DFloat.zeros(25,25) p z


1. How to find the closest value (to a given scalar) in an array ?  (★★☆)

    Python:
    ```python
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
Ruby:
```ruby

z = Numo::Int32.new(100).seq v = rand*100 index = (z-v).abs.min_index p z[index]


1. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

    Python:
    ```python
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                  ('y', float, 1)]),
                   ('color',    [ ('r', float, 1),
                                  ('g', float, 1),
                                  ('b', float, 1)])])
     print(Z)
Ruby:
```ruby

todo


1. Consider a random vector with shape (100,2) representing coordinates, find
   point by point distances (★★☆)

    Python:
    ```python
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)

# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
Ruby:
```ruby

1. How to convert a float (32 bits) array into an integer (32 bits) in place ?

    Python:
    ```python
Z = np.arange(10, dtype=np.int32)
Z = Z.astype(np.float32, copy=False)
Ruby:
```ruby

NArray does not support in-place type change


1. Consider the following file::

    ```
    1,2,3,4,5
    6,,,7,8
    ,,9,10,11
    ```

   How to read it ? (★★☆)

    Python:
    ```python
Z = np.genfromtxt("missing.dat", delimiter=",")
Ruby:
```ruby

z = Numo::NArray[*open("missing.dat").readlines.map{|l| l.chomp.split(",").map{|x| x.empty? ? Float::NAN : x.to_f}}]


1. What is the equivalent of `enumerate` for numpy arrays ? (★★☆)

    Python:
    ```python
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
    print(index, value)
for index in np.ndindex(Z.shape):
    print(index, Z[index])
Ruby:
```ruby

z = Numo::Int32.new(3,3).seq z.each_with_index{|x,*i| p [i,x]}


1. Generate a generic 2D Gaussian-like array (★★☆)

    Python:
    ```python
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
Ruby:
```ruby

x = Numo::DFloat.linspace(-1,1,10) y = Numo::DFloat.linspace(-1,1,10).expand_dims(1) d = Numo::NMath.sqrt(xx+yy) sigma, mu = 1.0, 0.0 g = Numo::NMath.exp(-( (d-mu)2 / ( 2.0 * sigma2 ) ) ) p g


1. How to randomly place p elements in a 2D array ? (★★☆)

    Python:
    ```python
# Author: Divakar

n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
Ruby:
```ruby

todo


1. Subtract the mean of each row of a matrix (★★☆)

    Python:
    ```python
# Author: Warren Weckesser

X = np.random.rand(5, 10)

# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)

# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)
Ruby:
```ruby

x = Numo::DFloat.new(5, 10).rand y = x - x.mean(1).expand_dims(1)


1. How to I sort an array by the nth column ? (★★☆)

    Python:
    ```python
# Author: Steve Tjoa

Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
Ruby:
```ruby

todo


1. How to tell if a given 2D array has null columns ? (★★☆)

    Python:
    ```python
# Author: Warren Weckesser

Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
Ruby:
```ruby

todo


1. Find the nearest value from a given value in an array (★★☆)

    Python:
    ```python
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
Ruby:
```ruby

z = Numo::DFloat.new(10).rand x = 0.5 m = z[(z - x).abs.min_index] p m

Clone this wiki locally