Roux Solution¶
import numpy as np
def make_roux(n):
"""returns a roux array of length n"""
roux = np.zeros(shape=(n,), dtype='int64')
nsquares = np.ceil(len(roux) / 2)
squares = (1 + np.arange(nsquares)) ** 2
roux[::-2] = squares
return roux
Explanation¶
-
Initialize an array of 0s with length
n
.n = 5 roux = np.zeros(shape=(n,), dtype='int64') print(roux) # [0 0 0 0 0]
n = 8 roux = np.zeros(shape=(n,), dtype='int64') print(roux) # [0 0 0 0 0 0 0 0]
n = 10 roux = np.zeros(shape=(n,), dtype='int64') print(roux) # [0 0 0 0 0 0 0 0 0 0 0 0]
-
Determine how many square numbers to generate.
We achieve this by dividing the length of
roux
by 2, then rounding up withnp.ceil()
.nsquares = np.ceil(len(roux) / 2) print(nsquares) # 3
nsquares = np.ceil(len(roux) / 2) print(nsquares) # 4
nsquares = np.ceil(len(roux) / 2) print(nsquares) # 6
-
Build the sequence of square numbers, 12, 22, ...,
nsquares
2.np.arange(nsquares)
makes the sequence 0, 1, ... (nsquares-1), so we add 1 to it and chain the result with**2
to square each element.squares = (1 + np.arange(nsquares)) ** 2 print(squares) # [1. 4. 9.]
squares = (1 + np.arange(nsquares)) ** 2 print(squares) # [ 1. 4. 9. 16.]
squares = (1 + np.arange(nsquares)) ** 2 print(squares) # [ 1. 4. 9. 16. 25. 36.]
Note that
squares
is an array of floats, not integers, as indicated by the trailing periods (e.g.1.
). -
Insert
squares
intoroux
.The goal is to insert
squares
intoroux
, but in reverse order starting from the end ofroux
. One way we can achieve this is by selecting every other element ofroux
starting from the end, moving backwards viaroux[::-2]
. Then we can mapsquares
to this subsetted view ofroux
.print(roux) # [0 0 0 0 0] print(squares) # [1. 4. 9.] roux[::-2] = squares print(roux) # [9 0 4 0 1]
print(roux) # [0 0 0 0 0 0 0 0] print(squares) # [1. 4. 9. 16.] roux[::-2] = squares print(roux) # [ 0 16 0 9 0 4 0 1]
print(roux) # [0 0 0 0 0 0 0 0 0 0 0 0] print(squares) # [1. 4. 9. 16. 25. 36.] roux[::-2] = squares print(roux) # [ 0 36 0 25 0 16 0 9 0 4 0 1]