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

Questo esercizio fa parte del corso

Practicing Coding Interview Questions in Python

Visualizza il corso

Istruzioni dell'esercizio

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

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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)
Modifica ed esegui il codice