ComeçarComece de graça

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 exercício faz parte do curso

Practicing Coding Interview Questions in Python

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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 e executar o código