Get startedGet started for free

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.

This exercise is part of the course

Practicing Coding Interview Questions in Python

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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)
Edit and Run Code