LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Practicing Coding Interview Questions in Python

Kurs anzeigen

Anleitung zur Übung

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

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

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)
Code bearbeiten und ausführen