ComenzarEmpieza gratis

Accessing subarrays

Let's access elements in NumPy arrays! Your task is to convert a square two-dimensional array square of size size to a list created by following a spiral pattern:

Traversing the matrix in spiral way

Rather than simply accessing certain slices, you will define a more general solution using a for loop (the solution should work for all the square two-dimensional arrays of odd size).

The module numpy is already imported as np.

You will need the reversed() function, which reverses an Iterable.

Este ejercicio forma parte del curso

Practicing Coding Interview Questions in Python

Ver curso

Instrucciones del ejercicio

  • Convert each part marked by a red arrow to a list.
  • Convert each part marked by a green arrow to a list.
  • Convert each part marked by a blue arrow to a list.
  • Convert each part marked by a magenta arrow to a list.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

spiral = []

for i in range(0, size):
    # Convert each part marked by any red arrow to a list
    spiral += list(square[i, ____:____])
    # Convert each part marked by any green arrow to a list
    spiral += list(square[____:____, size-i-1])
    # Convert each part marked by any blue arrow to a list
    spiral += list(reversed(square[size-i-1, ____:____]))
    # Convert each part marked by any magenta arrow to a list
    spiral += list(reversed(square[____:size-i-1, ____]))
        
print(spiral)
Editar y ejecutar código