Skip to content

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

  1. 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]
    
  2. Determine how many square numbers to generate.

    We achieve this by dividing the length of roux by 2, then rounding up with np.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
    
  3. Build the sequence of square numbers, 12, 22, ..., nsquares2.

    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.).

  4. Insert squares into roux.

    The goal is to insert squares into roux, but in reverse order starting from the end of roux. One way we can achieve this is by selecting every other element of roux starting from the end, moving backwards via roux[::-2]. Then we can map squares to this subsetted view of roux.

    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]
    

See the problem