This is Ruby/Numo::NArray version of 100 numpy exercises (Repository)

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

Python:

import numpy as np


Ruby:

In [1]:
require "numo/narray"

Out[1]:
true

#### 2. Print the numpy version and the configuration (★☆☆)¶

Python:

print(np.__version__)
np.show_config()


Ruby:

In [2]:
p Numo::NArray::VERSION

"0.9.0.3"

Out[2]:
"0.9.0.3"

#### 3. Create a null vector of size 10 (★☆☆)¶

Python:

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


Ruby:

In [3]:
z = Numo::DFloat.zeros(10)
p z

Numo::DFloat#shape=[10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Out[3]:
Numo::DFloat#shape=[10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#### 4. How to find the memory size of any array (★☆☆)¶

Python:

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))


Ruby:

In [4]:
z = Numo::DFloat.zeros(10,10)
printf "%d bytes", z.byte_size

800 bytes

#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)¶

Python:

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

Ruby:

In [5]:
ri 'Numo::DFloat#+'

Numo::DFloat#+

(from gem numo-narray-0.9.0.3)
Implementation from DFloat
------------------------------------------------------------------------------
+(p1)

------------------------------------------------------------------------------

[Numo::NArray] self + other



#### 6. 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:

In [6]:
z = Numo::DFloat.zeros(10)
z[4] = 1
p z

Numo::DFloat#shape=[10]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]

Out[6]:
Numo::DFloat#shape=[10]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]

#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)¶

Python:

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


Ruby:

In [7]:
z = Numo::DFloat[10..49]
p z

Numo::DFloat#shape=[40]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, ...]

Out[7]:
Numo::DFloat#shape=[40]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, ...]

#### 8. Reverse a vector (first element becomes last) (★☆☆)¶

Python:

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


Ruby:

In [9]:
z = Numo::Int32.new(50).seq
z = z.reverse

Out[9]:
Numo::Int32(view)#shape=[50]
[49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, ...]

#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)¶

Python:

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


Ruby:

In [10]:
z = Numo::Int32.new(3,3).seq
p z

Numo::Int32#shape=[3,3]
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]

Out[10]:
Numo::Int32#shape=[3,3]
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]

#### 10. 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:

In [11]:
nz = Numo::NArray[1,2,0,0,4,0].ne(0).where
p nz

Numo::Int32#shape=[3]
[0, 1, 4]

Out[11]:
Numo::Int32#shape=[3]
[0, 1, 4]

#### 11. Create a 3x3 identity matrix (★☆☆)¶

Python:

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


Ruby:

In [12]:
z = Numo::DFloat.eye(3)
p z

Numo::DFloat#shape=[3,3]
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]

Out[12]:
Numo::DFloat#shape=[3,3]
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]

#### 12. Create a 3x3x3 array with random values (★☆☆)¶

Python:

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


Ruby:

In [13]:
z = Numo::DFloat.new(3,3,3).rand
p z

Numo::DFloat#shape=[3,3,3]
[[[0.0617545, 0.373067, 0.794815],
[0.201042, 0.116041, 0.344032],
[0.539948, 0.737815, 0.165089]],
[[0.0508827, 0.108065, 0.0687079],
[0.904121, 0.478644, 0.342969],
[0.164541, 0.74603, 0.138994]],
[[0.411576, 0.292532, 0.869421],
[0.0854984, 0.688965, 0.159977],
[0.279215, 0.625155, 0.676329]]]

Out[13]:
Numo::DFloat#shape=[3,3,3]
[[[0.0617545, 0.373067, 0.794815],
[0.201042, 0.116041, 0.344032],
[0.539948, 0.737815, 0.165089]],
[[0.0508827, 0.108065, 0.0687079],
[0.904121, 0.478644, 0.342969],
[0.164541, 0.74603, 0.138994]],
[[0.411576, 0.292532, 0.869421],
[0.0854984, 0.688965, 0.159977],
[0.279215, 0.625155, 0.676329]]]

#### 13. 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:

In [14]:
z = Numo::DFloat.new(10,10).rand
zmin, zmax = z.minmax
p zmin, zmax

0.0007664325967829586
0.995590771731077

Out[14]:
[0.0007664325967829586, 0.995590771731077]

#### 14. Create a random vector of size 30 and find the mean value (★☆☆)¶

Python:

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


Ruby:

In [15]:
z = Numo::DFloat.new(30).rand
m = z.mean
p m

0.5609149765660713

Out[15]:
0.5609149765660713

#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)¶

Python:

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


Ruby:

In [16]:
z = Numo::DFloat.ones(10,10)
z[1..-2,1..-2] = 0
p z

Numo::DFloat#shape=[10,10]
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

Out[16]:
Numo::DFloat#shape=[10,10]
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)¶

Python:

Z = np.ones((5,5))
print(Z)


Ruby:

# todo: pad


#### 17. What is the result of the following expression? (★☆☆)¶

Python:

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


Ruby:

In [17]:
0 * Float::NAN
Float::NAN == Float::NAN
Float::INFINITY > Float::NAN
Float::NAN - Float::NAN
0.3 == 3 * 0.1

Out[17]:
false

#### 18. 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:

In [18]:
z = Numo::Int32.zeros(5,5)
z.diagonal(-1)[] = Numo::Int32[1..4]
p z

Numo::Int32#shape=[5,5]
[[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0]]

Out[18]:
Numo::Int32#shape=[5,5]
[[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0]]

#### 19. 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:

In [19]:
# todo: rangewithstep
x = Numo::Int32.new(1,8).seq
y = Numo::Int32.new(8,1).seq
z = (x+y)%2
p z

Numo::Int32#shape=[8,8]
[[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0]]

Out[19]:
Numo::Int32#shape=[8,8]
[[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0]]

#### 20. 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:

In [22]:
# NArray allows unraveled index access
z = Numo::Int32.new(6,7,8).seq
p z[100]

100

Out[22]:
100

#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)¶

Python:

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


Ruby:

# todo: tile


#### 22. 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:

In [23]:
z = Numo::DFloat.new(5,5).rand
zmin, zmax = z.minmax
z = (z - zmin)/(zmax - zmin)
p z

Numo::DFloat#shape=[5,5]
[[0.766088, 0.769435, 0.641326, 0.836021, 0.287046],
[0.838608, 0.290923, 0.0930798, 0.235153, 0.57146],
[0.167737, 0.548881, 1, 0.771149, 0.683695],
[0.766882, 0.486607, 0.942667, 0, 0.45248],
[0.801575, 0.23934, 0.267108, 0.536452, 0.382229]]

Out[23]:
Numo::DFloat#shape=[5,5]
[[0.766088, 0.769435, 0.641326, 0.836021, 0.287046],
[0.838608, 0.290923, 0.0930798, 0.235153, 0.57146],
[0.167737, 0.548881, 1, 0.771149, 0.683695],
[0.766882, 0.486607, 0.942667, 0, 0.45248],
[0.801575, 0.23934, 0.267108, 0.536452, 0.382229]]

#### 23. Create a custom dtype that describes a color as four unisgned bytes (RGBA) (★☆☆)¶

Python:

color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])


Ruby:

In [24]:
# todo: record
color = Numo::Struct.new do
uint8 "r"
uint8 "g"
uint8 "b"
uint8 "a"
end

Out[24]:
#<Class:0x007f8cfab26a68>

#### 24. 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:

In [25]:
x = Numo::DFloat.ones(5,3)
y = Numo::DFloat.ones(3,2)
z = x.dot y
p z

Numo::DFloat#shape=[5,2]
[[3, 3],
[3, 3],
[3, 3],
[3, 3],
[3, 3]]

Out[25]:
Numo::DFloat#shape=[5,2]
[[3, 3],
[3, 3],
[3, 3],
[3, 3],
[3, 3]]

#### 25. 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
print(Z)


Ruby:

In [27]:
z = Numo::Int32.new(11).seq
z[(3 < z) & (z <= 8)] *= -1
p z

Numo::Int32#shape=[11]
[0, 1, 2, 3, -4, -5, -6, -7, -8, 9, 10]

Out[27]:
Numo::Int32#shape=[11]
[0, 1, 2, 3, -4, -5, -6, -7, -8, 9, 10]

#### 26. What is the output of the following script? (★☆☆)¶

Python:

# Author: Jake VanderPlas

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))


Ruby:

In [15]:
p [*0...5,-1].inject(:+)
p Numo::Int32[0...5].sum(-1)

9
10

Out[15]:
10

#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)¶

Python:

Z = np.arange(5)
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z


Ruby:

In [16]:
z = Numo::Int32.new(5).seq
z**z
2 << z >> 2
z <- z
1i*z
z/1/1
z<z>z

TypeError: no implicit conversion of Numo::Int32 into Integer
(pry):51:in <<'
(pry):51:in <main>'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in evaluate_ruby'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:323:in handle_line'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:243:in block (2 levels) in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in block in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:65:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:12:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:87:in execute_request'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:47:in dispatch'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:37:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:70:in run_kernel'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:34:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/bin/iruby:5:in <top (required)>'
/usr/local/bin/iruby:22:in <main>'

#### 28. What are the result of the following expressions?¶

Python:

print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))


Ruby:

In [17]:
p Numo::Int32[0] / Numo::Int32[0]
p Numo::DFloat[Float::NAN].cast_to(Numo::Int32).cast_to(Numo::DFloat)

ZeroDivisionError: error in NArray operation
(pry):56:in /'
(pry):56:in <main>'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in evaluate_ruby'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:323:in handle_line'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:243:in block (2 levels) in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in block in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:65:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:12:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:87:in execute_request'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:47:in dispatch'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:37:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:70:in run_kernel'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:34:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/bin/iruby:5:in <top (required)>'
/usr/local/bin/iruby:22:in <main>'

#### 29. How to round away from zero a float array ? (★☆☆)¶

Python:

# Author: Charles R Harris

Z = np.random.uniform(-10,+10,10)
print (np.trunc(Z + np.copysign(0.5, Z)))


Ruby:

In [18]:
z = Numo::DFloat.new(10).rand(-10,+10)
p (z + (0.5*z.sign)).trunc
# todo: copysign

Numo::DFloat#shape=[10]
[-7, -0, 10, -5, -7, -1, -10, -3, -1, -5]

Out[18]:
Numo::DFloat#shape=[10]
[-7, -0, 10, -5, -7, -1, -10, -3, -1, -5]

#### 30. How to find common values between two arrays? (★☆☆)¶

Python:

Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))


Ruby:

In [19]:
# todo: intersect1d


#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)¶

Python:

A = np.ones(3)*1
B = np.ones(3)*2
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)


Ruby:

In [3]:
a = Numo::DFloat.new(3).fill(1)
b = Numo::DFloat.new(3).fill(2)
p (a+b)*(-a/2)
(a+b.inplace)*(-a.inplace/2)
p b

Numo::DFloat#shape=[3]
[-1.5, -1.5, -1.5]
Numo::DFloat#shape=[3]
[-1.5, -1.5, -1.5]

Out[3]:
Numo::DFloat#shape=[3]
[-1.5, -1.5, -1.5]

#### 36. Extract the integer part of a random array using 5 different methods (★★☆)¶

Python:

Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))


Ruby:

In [4]:
z = Numo::DFloat.new(10).rand(10)

p z - z%1
p z.floor
p z.ceil - 1
p z.cast_to(Numo::Int32)
p z.trunc

Numo::DFloat#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]
Numo::DFloat#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]
Numo::DFloat#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]
Numo::Int32#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]
Numo::DFloat#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]

Out[4]:
Numo::DFloat#shape=[10]
[0, 3, 7, 2, 1, 3, 5, 7, 1, 0]

#### 37. 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:

In [5]:
z = Numo::DFloat.zeros(5,5)
z += Numo::Int32.new(5).seq
p z

Numo::DFloat#shape=[5,5]
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]

Out[5]:
Numo::DFloat#shape=[5,5]
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]

#### 39. 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:

In [6]:
z = Numo::DFloat.linspace(0,1,12)[1..-2]
p z

Numo::DFloat(view)#shape=[10]
[0.0909091, 0.181818, 0.272727, 0.363636, 0.454545, 0.545455, 0.636364, ...]

Out[6]:
Numo::DFloat(view)#shape=[10]
[0.0909091, 0.181818, 0.272727, 0.363636, 0.454545, 0.545455, 0.636364, ...]

#### 40. Create a random vector of size 10 and sort it (★★☆)¶

Python:

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


Ruby:

In [7]:
z = Numo::DFloat.new(10).rand
z = z.sort
p z

Numo::DFloat#shape=[10]
[0.0687079, 0.108065, 0.138994, 0.164541, 0.292532, 0.342969, 0.411576, ...]

Out[7]:
Numo::DFloat#shape=[10]
[0.0687079, 0.108065, 0.138994, 0.164541, 0.292532, 0.342969, 0.411576, ...]

#### 43. Make an array immutable (read-only) (★★☆)¶

Python:

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


Ruby:

In [3]:
z = Numo::DFloat.zeros(10)
z.freeze
z[0] = 1

RuntimeError: cannot write to frozen NArray.
(pry):7:in []='
(pry):7:in <main>'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:355:in evaluate_ruby'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:323:in handle_line'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:243:in block (2 levels) in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:242:in block in eval'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in catch'
/var/lib/gems/2.1.0/gems/pry-0.10.4/lib/pry/pry_instance.rb:241:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:65:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/backend.rb:12:in eval'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:87:in execute_request'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:47:in dispatch'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/kernel.rb:37:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:70:in run_kernel'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/lib/iruby/command.rb:34:in run'
/var/lib/gems/2.1.0/gems/iruby-0.2.9/bin/iruby:5:in <top (required)>'
/usr/local/bin/iruby:22:in <main>'

#### 44. 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(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)


Ruby:

In [4]:
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

Numo::DFloat#shape=[10]
[0.378143, 0.819847, 0.363075, 0.914284, 0.172752, 0.128057, 1.023, ...]
Numo::DFloat#shape=[10]
[1.40675, 0.247746, 1.24548, 0.939032, 0.298976, 0.566331, 0.486892, ...]

Out[4]:
Numo::DFloat#shape=[10]
[1.40675, 0.247746, 1.24548, 0.939032, 0.298976, 0.566331, 0.486892, ...]

#### 45. 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:

In [5]:
z = Numo::DFloat.new(10).rand
z[z.max_index] = 0
p z

Numo::DFloat#shape=[10]
[0, 0.0854984, 0.688965, 0.159977, 0.279215, 0.625155, 0.676329, ...]

Out[5]:
Numo::DFloat#shape=[10]
[0, 0.0854984, 0.688965, 0.159977, 0.279215, 0.625155, 0.676329, ...]

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

Python:

Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])


Ruby:

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

86

Out[3]:
86

#### 54. How to read the following file? (★★☆)¶

Python:

from io import StringIO

# Fake file
s = StringIO("""1, 2, 3, 4, 5\n
6,  ,  , 7, 8\n
,  , 9,10,11\n""")
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)


Ruby:

In [4]:
require "stringio"
s = StringIO.new("1, 2, 3, 4, 5
6,  ,  , 7, 8
,  , 9,10,11")
z = Numo::NArray[*s.readlines.map{|l| l.split(",").map{|x| x.strip.empty? ? Float::NAN : x.to_f}}]

Out[4]:
Numo::DFloat#shape=[3,5]
[[1, 2, 3, 4, 5],
[6, nan, nan, 7, 8],
[nan, nan, 9, 10, 11]]

#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)¶

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:

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

[[0, 0], 0]
[[0, 1], 1]
[[0, 2], 2]
[[1, 0], 3]
[[1, 1], 4]
[[1, 2], 5]
[[2, 0], 6]
[[2, 1], 7]
[[2, 2], 8]

Out[5]:
Numo::Int32#shape=[3,3]
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]

#### 56. Generate a generic 2D Gaussian-like array (★★☆)¶

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:

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

Numo::DFloat#shape=[10,10]
[[0.367879, 0.448221, 0.519795, 0.573753, 0.602798, 0.602798, 0.573753, ...],
[0.448221, 0.546108, 0.633313, 0.699056, 0.734444, 0.734444, 0.699056, ...],
[0.519795, 0.633313, 0.734444, 0.810684, 0.851723, 0.851723, 0.810684, ...],
[0.573753, 0.699056, 0.810684, 0.894839, 0.940138, 0.940138, 0.894839, ...],
[0.602798, 0.734444, 0.851723, 0.940138, 0.98773, 0.98773, 0.940138, ...],
[0.602798, 0.734444, 0.851723, 0.940138, 0.98773, 0.98773, 0.940138, ...],
[0.573753, 0.699056, 0.810684, 0.894839, 0.940138, 0.940138, 0.894839, ...],
[0.519795, 0.633313, 0.734444, 0.810684, 0.851723, 0.851723, 0.810684, ...],
[0.448221, 0.546108, 0.633313, 0.699056, 0.734444, 0.734444, 0.699056, ...],
[0.367879, 0.448221, 0.519795, 0.573753, 0.602798, 0.602798, 0.573753, ...]]

Out[6]:
Numo::DFloat#shape=[10,10]
[[0.367879, 0.448221, 0.519795, 0.573753, 0.602798, 0.602798, 0.573753, ...],
[0.448221, 0.546108, 0.633313, 0.699056, 0.734444, 0.734444, 0.699056, ...],
[0.519795, 0.633313, 0.734444, 0.810684, 0.851723, 0.851723, 0.810684, ...],
[0.573753, 0.699056, 0.810684, 0.894839, 0.940138, 0.940138, 0.894839, ...],
[0.602798, 0.734444, 0.851723, 0.940138, 0.98773, 0.98773, 0.940138, ...],
[0.602798, 0.734444, 0.851723, 0.940138, 0.98773, 0.98773, 0.940138, ...],
[0.573753, 0.699056, 0.810684, 0.894839, 0.940138, 0.940138, 0.894839, ...],
[0.519795, 0.633313, 0.734444, 0.810684, 0.851723, 0.851723, 0.810684, ...],
[0.448221, 0.546108, 0.633313, 0.699056, 0.734444, 0.734444, 0.699056, ...],
[0.367879, 0.448221, 0.519795, 0.573753, 0.602798, 0.602798, 0.573753, ...]]

#### 58. Subtract the mean of each row of a matrix (★★☆)¶

Python:

# Author: Warren Weckesser

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

Y = X - X.mean(axis=1, keepdims=True)

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

print(Y)


Ruby:

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

Out[7]:
Numo::DFloat#shape=[5,10]
[[-0.276694, 0.0346182, 0.456367, -0.137406, -0.222408, 0.00558358, ...],
[-0.257554, -0.29691, 0.538503, 0.113026, -0.0226486, -0.201077, ...],
[0.49633, -0.287593, 0.315874, -0.213114, -0.0938766, 0.252064, 0.303238, ...],
[-0.0359266, -0.116908, 0.508809, 0.423319, -0.309937, -0.404925, ...],
[-0.168796, -0.165424, 0.464085, -0.0274508, 0.0251129, 0.0339921, ...]]

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

Python:

# Author: Steve Tjoa

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


Ruby:

In [8]:
z = Numo::Int32.new(3,3).rand(10)
p z
p z[z[true,1].sort_index,true]

Numo::Int32#shape=[3,3]
[[7, 3, 0],
[2, 5, 0],
[2, 7, 7]]
Numo::Int32(view)#shape=[3,3]
[[7, 3, 0],
[2, 5, 0],
[2, 7, 7]]

Out[8]:
Numo::Int32(view)#shape=[3,3]
[[7, 3, 0],
[2, 5, 0],
[2, 7, 7]]

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

Python:

# Author: Warren Weckesser

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


Ruby:

In [2]:
z = Numo::Int32.new(3,10).rand(3)
(~z.ne(0).any?(0)).any?

Out[2]:
true

#### 61. Find the nearest value from a given value in an array (★★☆)¶

Python:

Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)


Ruby:

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

0.4115760120668863

Out[3]:
0.4115760120668863

#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)¶

Python:

# Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))


Ruby:

In [4]:
# todo: unique
w,h = 16,16
i = Numo::UInt32.new(h,w,3).rand(2)
f = i[false,0]*256*256 + i[false,1]*256 +i[false,2]
p f.flatten.sort.to_a.uniq

[0, 1, 256, 257, 65536, 65793, 65792, 65537]

Out[4]:
[0, 1, 256, 257, 65536, 65793, 65792, 65537]

#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)¶

Python:

A = np.random.randint(0,10,(3,4,3,4))
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum)


Ruby:

In [5]:
a = Numo::Int32.new(3,4,3,4).rand(10)
sum = a.sum(-2,-1)
p sum

Numo::Int32#shape=[3,4]
[[80, 51, 48, 48],
[51, 58, 56, 43],
[59, 61, 73, 54]]

Out[5]:
Numo::Int32#shape=[3,4]
[[80, 51, 48, 48],
[51, 58, 56, 43],
[59, 61, 73, 54]]

#### 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)¶

Python:

# Author: Jaime Fernández del Río

D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)


Ruby:

# todo: bincount


#### 69. How to get the diagonal of a dot product? (★★★)¶

Python:

# Author: Mathieu Blondel

A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))

# Slow version
np.diag(np.dot(A, B))

# Fast version
np.sum(A * B.T, axis=1)

# Faster version
np.einsum("ij,ji->i", A, B)


Ruby:

In [6]:
a = Numo::DFloat.new(3,3).seq
b = Numo::DFloat.new(3,3).seq
p a.mulsum(b.transpose,1)
# speed?

Numo::DFloat#shape=[3]
[15, 54, 111]

Out[6]:
Numo::DFloat#shape=[3]
[15, 54, 111]

#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)¶

Python:

# Author: Warren Weckesser

Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)


Ruby:

In [7]:
z = Numo::NArray[1,2,3,4,5]
nz = 3
z0 = Numo::Int32.zeros(z.size + (z.size-1)*(nz))
# todo: rangewithstep
# z0[(0..-1).step(nz+1)] = z
# p z0

Out[7]:
Numo::Int32#shape=[17]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)¶

Python:

A = np.ones((5,5,3))
B = 2*np.ones((5,5))
print(A * B[:,:,None])


Ruby:

In [8]:
a = Numo::Int32.ones(5,5,3)
b = Numo::Int32.new(5,5).fill(2)
p a * b[:*,:*,:-]

Numo::Int32#shape=[5,5,3]
[[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
...

Out[8]:
Numo::Int32#shape=[5,5,3]
[[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
...

#### 72. How to swap two rows of an array? (★★★)¶

Python:

# Author: Eelco Hoogendoorn

A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print(A)


Ruby:

In [9]:
a = Numo::Int32.new(5,5).seq
a[[0,1],true] = a[[1,0],true].copy
p a
# todo: identity check between read/write array

Numo::Int32#shape=[5,5]
[[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]

Out[9]:
Numo::Int32#shape=[5,5]
[[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]

#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)¶

Python:

# Author: Nicolas P. Rougier

faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print(G)


Ruby:

# todo: roll


#### 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)¶

Python:

# Author: Jaime Fernández del Río

C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print(A)


Ruby:

# todo: bincount, repeat


#### 75. How to compute averages using a sliding window over an array? (★★★)¶

Python:

# Author: Jaime Fernández del Río

def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))


Ruby:

In [2]:
def moving_average(a, n=3)
ret = a.cumsum
ret[n..-1] = ret[n..-1] - ret[0..-n-1]
ret[n-1..-1] / n
end
z = Numo::DFloat.new(20).seq
p moving_average(z, 3)

Numo::DFloat#shape=[18]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

Out[2]:
Numo::DFloat#shape=[18]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

#### 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)¶

Python:

# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks

def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.itemsize, a.itemsize)
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)


Ruby:

# no module: stride_tricks


#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)¶

Python:

# Author: Nathaniel J. Smith

Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)

Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)


Ruby:

In [3]:
# todo: logical_not
z = Numo::Int32.new(100).rand(2)
p z
z.inplace ^ 1
p z

z = Numo::DFloat.new(100).rand(-1,1)
p z
-z.inplace
p z

Numo::Int32#shape=[100]
[0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, ...]
Numo::Int32#shape=[100]
[1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, ...]
Numo::DFloat#shape=[100]
[-0.00105903, 0.140595, -0.671175, 0.782669, 0.406039, -0.54762, 0.86998, ...]
Numo::DFloat#shape=[100]
[0.00105903, -0.140595, 0.671175, -0.782669, -0.406039, 0.54762, -0.86998, ...]

Out[3]:
Numo::DFloat#shape=[100]
[0.00105903, -0.140595, 0.671175, -0.782669, -0.406039, 0.54762, -0.86998, ...]

#### 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)¶

Python:

def distance(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))

P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p  = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))


Ruby:

In [4]:
def distance(p0, p1, p)
t = p1 - p0
l = (t**2).sum(1)
u = -((p0[true,0]-p[false,0])*t[true,0] + (p0[true,1]-p[false,1])*t[true,1]) / l
u = u.reshape(u.size,1)
d = p0 + u*t - p
return Numo::NMath.sqrt((d**2).sum(1))
end

p0 = Numo::DFloat.new(10,2).rand(-10,10)
p1 = Numo::DFloat.new(10,2).rand(-10,10)
p  = Numo::DFloat.new( 1,2).rand(-10,10)
p distance(p0, p1, p)

Numo::DFloat#shape=[10]
[4.40292, 8.02008, 14.77, 16.1336, 16.0784, 7.29705, 9.79877, 10.7509, ...]

Out[4]:
Numo::DFloat#shape=[10]
[4.40292, 8.02008, 14.77, 16.1336, 16.0784, 7.29705, 9.79877, 10.7509, ...]

#### 79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)¶

Python:

# Author: Italmassov Kuanysh

# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))


Ruby:

In [5]:
p0 = Numo::DFloat.new(10,2).rand(-10,10)
p1 = Numo::DFloat.new(10,2).rand(-10,10)
p  = Numo::DFloat.new(10,2).rand(-10,10)
p a = p.shape[0].times.map{|i| distance(p0, p1, p.slice(i,true))}
# todo: concat narray

[Numo::DFloat#shape=[10]
[4.02299, 3.7767, 7.22074, 2.65235, 4.03999, 0.0493129, 5.89712, 0.821607, ...], Numo::DFloat#shape=[10]
[4.06287, 10.2757, 5.22386, 9.17308, 3.49263, 6.51912, 12.1396, 6.87145, ...], Numo::DFloat#shape=[10]
[12.2731, 4.95469, 14.9322, 6.10746, 12.3248, 8.71038, 4.51429, 8.38228, ...], Numo::DFloat#shape=[10]
[7.29208, 11.2986, 5.80238, 9.93285, 11.5081, 9.4783, 9.65492, 10.33, ...], Numo::DFloat#shape=[10]
[7.42679, 14.6827, 6.16027, 13.4397, 8.20325, 10.8814, 16.0162, 11.3742, ...], Numo::DFloat#shape=[10]
[8.90535, 14.3727, 6.22079, 12.941, 13.1026, 11.9889, 13.0645, 12.8597, ...], Numo::DFloat#shape=[10]
[10.121, 14.4822, 11.257, 13.8115, 7.24394, 11.2893, 17.1786, 11.2277, ...], Numo::DFloat#shape=[10]
[9.10298, 2.80676, 12.3148, 3.95976, 7.48986, 5.13894, 6.17195, 4.37329, ...], Numo::DFloat#shape=[10]
[0.720696, 7.46437, 3.14777, 6.04, 4.88395, 4.03443, 8.16959, 4.84799, ...], Numo::DFloat#shape=[10]
[2.82967, 10.3413, 0.872794, 8.92055, 6.33658, 6.80721, 10.889, 7.56309, ...]]

Out[5]:
[Numo::DFloat#shape=[10]
[4.02299, 3.7767, 7.22074, 2.65235, 4.03999, 0.0493129, 5.89712, 0.821607, ...], Numo::DFloat#shape=[10]
[4.06287, 10.2757, 5.22386, 9.17308, 3.49263, 6.51912, 12.1396, 6.87145, ...], Numo::DFloat#shape=[10]
[12.2731, 4.95469, 14.9322, 6.10746, 12.3248, 8.71038, 4.51429, 8.38228, ...], Numo::DFloat#shape=[10]
[7.29208, 11.2986, 5.80238, 9.93285, 11.5081, 9.4783, 9.65492, 10.33, ...], Numo::DFloat#shape=[10]
[7.42679, 14.6827, 6.16027, 13.4397, 8.20325, 10.8814, 16.0162, 11.3742, ...], Numo::DFloat#shape=[10]
[8.90535, 14.3727, 6.22079, 12.941, 13.1026, 11.9889, 13.0645, 12.8597, ...], Numo::DFloat#shape=[10]
[10.121, 14.4822, 11.257, 13.8115, 7.24394, 11.2893, 17.1786, 11.2277, ...], Numo::DFloat#shape=[10]
[9.10298, 2.80676, 12.3148, 3.95976, 7.48986, 5.13894, 6.17195, 4.37329, ...], Numo::DFloat#shape=[10]
[0.720696, 7.46437, 3.14777, 6.04, 4.88395, 4.03443, 8.16959, 4.84799, ...], Numo::DFloat#shape=[10]
[2.82967, 10.3413, 0.872794, 8.92055, 6.33658, 6.80721, 10.889, 7.56309, ...]]

#### 80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)¶

Python:

# Author: Nicolas Rougier

Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill  = 0
position = (1,1)

R = np.ones(shape, dtype=Z.dtype)*fill
P  = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)

R_start = np.zeros((len(shape),)).astype(int)
R_stop  = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop  = (P+Rs//2)+Rs%2

R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()

r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]
print(Z)
print(R)


Ruby:

# todo: minimum, maximum


#### 81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)¶

Python:

# Author: Stefan van der Walt

Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)


Ruby:

# no moudle: stride_tricks


#### 82. Compute a matrix rank (★★★)¶

Python:

# Author: Stefan van der Walt

Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)


Ruby:

# todo: svd


#### 83. How to find the most frequent value in an array?¶

Python:

Z = np.random.randint(0,10,50)
print(np.bincount(Z).argmax())


Ruby:

# todo: bincount


#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)¶

Python:

# Author: Chris Barker

Z = np.random.randint(0,5,(10,10))
n = 3
i = 1 + (Z.shape[0]-3)
j = 1 + (Z.shape[1]-3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)


Ruby:

# no module: stride_tricks


#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)¶

Python:

# Author: Eric O. Lebigot
# Note: only works for 2d array and value setting using indices

class Symetric(np.ndarray):
def __setitem__(self, index, value):
i,j = index
super(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)

def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)

S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)


Ruby:

In [6]:
module Symetric
def []=(i,j,value)
super(i,j,value)
super(j,i,value) if i != j
end
end

def symetric(z)
y = z + z.transpose
y.diagonal.store(z.diagonal)
y.extend(Symetric)
end

s = symetric(Numo::Int32.new(5,5).rand(10))
s[2,3] = 42
p s

Numo::Int32#shape=[5,5]
[[8, 6, 5, 8, 12],
[6, 7, 9, 11, 10],
[5, 9, 5, 42, 6],
[8, 11, 42, 3, 16],
[12, 10, 6, 16, 0]]

Out[6]:
Numo::Int32#shape=[5,5]
[[8, 6, 5, 8, 12],
[6, 7, 9, 11, 10],
[5, 9, 5, 42, 6],
[8, 11, 42, 3, 16],
[12, 10, 6, 16, 0]]

#### 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)¶

Python:

# Author: Stefan van der Walt

p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)

# It works, because:
# M is (p,n,n)
# V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.


Ruby:

In [7]:
p, n = 10, 20
m = Numo::DFloat.ones(p,n,n)
v = Numo::DFloat.ones(p,n,1)
s = m.transpose(0,2,1).mulsum(v,0,1)
p s
# todo: tensordot?

Numo::DFloat#shape=[20]
[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, ...]

Out[7]:
Numo::DFloat#shape=[20]
[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, ...]

#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)¶

Python:

# Author: Robert Kern

Z = np.ones((16,16))
k = 4
np.arange(0, Z.shape[1], k), axis=1)
print(S)


Ruby:

In [8]:
n, k = 16, 4
z = Numo::DFloat.ones(n,n)
s = z.reshape(n/k,k,n/k,k).sum(1,3)
# todo: reduceat?

Out[8]:
Numo::DFloat#shape=[4,4]
[[16, 16, 16, 16],
[16, 16, 16, 16],
[16, 16, 16, 16],
[16, 16, 16, 16]]

#### 88. How to implement the Game of Life using numpy arrays? (★★★)¶

Python:

# Author: Nicolas Rougier

def iterate(Z):
# Count neighbours
N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2]                + Z[1:-1,2:] +
Z[2:  ,0:-2] + Z[2:  ,1:-1] + Z[2:  ,2:])

# Apply rules
birth = (N==3) & (Z[1:-1,1:-1]==0)
survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
Z[...] = 0
Z[1:-1,1:-1][birth | survive] = 1
return Z

Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z)
print(Z)


Ruby:

In [9]:
def iterate(z)
# Count neighbours
n = z[0..-3,0..-3] + z[0..-3,1..-2] + z[0..-3,2..-1] +
z[1..-2,0..-3]                  + z[1..-2,2..-1] +
z[2..-1,0..-3] + z[2..-1,1..-2] + z[2..-1,2..-1]

# Apply rules
birth = n.eq(3) & z[1..-2,1..-2].eq(0)
survive = (n.eq(2) | n.eq(3)) & z[1..-2,1..-2].eq(1)
z[] = 0
#z[1..-2,1..-2][birth | survive] = 1
y = z[0..-3,0..-3].copy
y[birth | survive] = 1
z[1..-2,1..-2] = y
end

z = Numo::Int32.new(50,50).rand(2)
100.times{ iterate(z) }
p z

Numo::Int32#shape=[50,50]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ...],
...

Out[9]:
Numo::Int32#shape=[50,50]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, ...],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ...],
...

#### 89. How to get the n largest values of an array (★★★)¶

Python:

Z = np.arange(10000)
np.random.shuffle(Z)
n = 5

# Slow
print (Z[np.argsort(Z)[-n:]])

# Fast
print (Z[np.argpartition(-Z,n)[:n]])


Ruby:

In [10]:
z = Numo::DFloat.new(10000).rand
n = 5
p z[z.sort_index[-n..-1]]
# todo: shuffle, argpartition

Numo::DFloat(view)#shape=[5]
[0.999617, 0.999781, 0.999866, 0.999873, 0.999884]

Out[10]:
Numo::DFloat(view)#shape=[5]
[0.999617, 0.999781, 0.999866, 0.999873, 0.999884]

#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)¶

Python:

# Author: Stefan Van der Walt

def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)

ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T

for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]

return ix

print (cartesian(([1, 2, 3], [4, 5], [6, 7])))


Ruby:

In [11]:
def cartesian(*arrays)
arrays = arrays.map{|a| Numo::Int32.cast(a)}
shape = arrays.map{|x| x.size}
asz = arrays.size

ix = Numo::Int32.zeros(*shape, asz)
arrays.each_with_index do |arr,n|
s = [1]*asz
s[n] = arr.size
ix[false,n] = arr.reshape(*s)
end
return ix.reshape(ix.size/asz,asz)
end

p cartesian([1, 2, 3], [4, 5], [6, 7])

Numo::Int32#shape=[12,3]
[[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]]

Out[11]:
Numo::Int32#shape=[12,3]
[[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]]

#### 91. How to create a record array from a regular array? (★★★)¶

Python:

Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T,
names='col1, col2, col3',
formats = 'S8, f8, i8')
print(R)


Ruby:

# todo: record


#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)¶

Python:

# Author: Ryan G.

x = np.random.rand(5e7)

%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)


Ruby:

In [2]:
x = Numo::DFloat.new(5e7).rand
x**3 # probably fast

Out[2]:
Numo::DFloat#shape=[50000000]
[0.000235508, 0.051923, 0.50211, 0.00812571, 0.00156255, 0.040719, ...]

#### 93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)¶

Python:

# Author: Gabe Schwartz

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

C = (A[..., np.newaxis, np.newaxis] == B)
rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0]
print(rows)


Ruby:

In [3]:
a = Numo::Int32.new(8,3).rand(5)
b = Numo::Int32.new(2,2).rand(5)
c = a[false,:new,:new].eq b
rows = (c.count_true(1,2,3) >= b.shape[1]).where
p rows

Numo::Int32#shape=[6]
[0, 1, 2, 5, 6, 7]

Out[3]:
Numo::Int32#shape=[6]
[0, 1, 2, 5, 6, 7]

#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)¶

Python:

# Author: Robert Kern

Z = np.random.randint(0,5,(10,3))
E = np.logical_and.reduce(Z[:,1:] == Z[:,:-1], axis=1)
U = Z[~E]
print(Z)
print(U)


Ruby:

In [4]:
z = Numo::Int32.new(10,3).rand(5)
e = (z[true,1..-1].eq z[true,0..-2]).all?(1)
u = z[(~e).where,true]
p z
p u

Numo::Int32#shape=[10,3]
[[0, 2, 1],
[3, 1, 0],
[3, 1, 2],
[2, 4, 4],
[0, 3, 0],
[4, 3, 3],
[4, 3, 2],
[2, 0, 2],
[2, 3, 2],
[2, 3, 4]]
Numo::Int32(view)#shape=[10,3]
[[0, 2, 1],
[3, 1, 0],
[3, 1, 2],
[2, 4, 4],
[0, 3, 0],
[4, 3, 3],
[4, 3, 2],
[2, 0, 2],
[2, 3, 2],
[2, 3, 4]]

Out[4]:
Numo::Int32(view)#shape=[10,3]
[[0, 2, 1],
[3, 1, 0],
[3, 1, 2],
[2, 4, 4],
[0, 3, 0],
[4, 3, 3],
[4, 3, 2],
[2, 0, 2],
[2, 3, 2],
[2, 3, 4]]

#### 95. Convert a vector of ints into a matrix binary representation (★★★)¶

Python:

# Author: Warren Weckesser

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])

# Author: Daniel T. McDonald

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))


Ruby:

# todo: bit


#### 96. Given a two dimensional array, how to extract unique rows? (★★★)¶

Python:

# Author: Jaime Fernández del Río

Z = np.random.randint(0,2,(6,3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print(uZ)


Ruby:

# todo: unique row


#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)¶

Python:

# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/

A = np.random.uniform(0,1,10)
B = np.random.uniform(0,1,10)

np.einsum('i->', A)       # np.sum(A)
np.einsum('i,i->i', A, B) # A * B
np.einsum('i,i', A, B)    # np.inner(A, B)
np.einsum('i,j', A, B)    # np.outer(A, B)


Ruby:

In [5]:
# no method: einsum
a = Numo::DFloat.new(10).rand(0,1)
b = Numo::DFloat.new(10).rand(0,1)

a.sum           # np.sum(A)
a*b             # A * B
a.mulsum(b)     # np.inner(A, B)
a[false,:new]*b # np.outer(A, B)

Out[5]:
Numo::DFloat#shape=[10,10]
[[0.418361, 0.252631, 0.168549, 0.367414, 0.0409535, 0.365022, 0.22084, ...],
[0.369513, 0.223134, 0.148869, 0.324515, 0.0361717, 0.322402, 0.195055, ...],
[0.575741, 0.347666, 0.231954, 0.505629, 0.0563594, 0.502337, 0.303916, ...],
[0.423199, 0.255553, 0.170498, 0.371663, 0.0414271, 0.369243, 0.223394, ...],
[0.0554262, 0.0334696, 0.02233, 0.0486766, 0.00542569, 0.0483596, ...],
[0.285368, 0.172322, 0.114968, 0.250617, 0.0279347, 0.248985, 0.150637, ...],
[0.398275, 0.240502, 0.160457, 0.349775, 0.0389873, 0.347497, 0.210238, ...],
[0.21605, 0.130464, 0.0870418, 0.18974, 0.0211492, 0.188505, 0.114046, ...],
[0.343856, 0.20764, 0.138532, 0.301982, 0.0336601, 0.300016, 0.181511, ...],
[0.0467036, 0.0282024, 0.0188159, 0.0410162, 0.00457183, 0.0407492, ...]]

#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?¶

Python:

# Author: Bas Swinckels

phi = np.arange(0, 10*np.pi, 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)

dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr)                # integrate path
r_int = np.linspace(0, r.max(), 200) # regular spaced path
x_int = np.interp(r_int, r, x)       # integrate path
y_int = np.interp(r_int, r, y)


Ruby:

# todo: interp


#### 99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)¶

Python:

# Author: Evgeni Burovski

X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])


Ruby:

#### 100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)¶

Python:

# Author: Jessica B. Hamrick

X = np.random.randn(100) # random 1D array
N = 1000 # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(1)
confint = np.percentile(means, [2.5, 97.5])
print(confint)


Ruby:

In [2]:
x = Numo::DFloat.new(100).rand
n = 1000 # number of bootstrap samples
idx = Numo::Int32.new(n, x.size).rand(x.size)
means = x[idx].mean(1)
confint = means[means.sort_index[means.size/100.0*Numo::DFloat[2.5, 97.5]]]
p confint
# todo: percentile, rand_norm

Numo::DFloat(view)#shape=[2]
[0.345385, 0.449567]

Out[2]:
Numo::DFloat(view)#shape=[2]
[0.345385, 0.449567]
In [ ]: