50 XP

67. Spiral order

Intermediate grids simulation

A grid is a list of rows, each a list of the same length. Write a function spiral(grid) that returns all of the grid's items in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row, up the left column, and keep circling inward until every item has been read once.

  • Every item appears exactly once in the result.
  • A grid with a single row or a single column is read straight through.
  • An empty grid [] gives [].

Example 1

Inputgrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output[1, 2, 3, 6, 9, 8, 7, 4, 5]
ExplanationRound the edge clockwise, then the middle.

Example 2

Inputgrid = [[1, 2, 3, 4], [5, 6, 7, 8]]
Output[1, 2, 3, 4, 8, 7, 6, 5]
ExplanationAlong the top, then back along the bottom.

Example 3

Inputgrid = [[1], [2], [3]]
Output[1, 2, 3]
ExplanationOne column, read top to bottom.

Constraints

  • grid has 0 to 10 rows; every row has the same number of items, 1 to 10.
  • The items are whole numbers.

Submit also runs 8 more tests you can't see.

Practises Lists (lesson 9).

Code
def spiral(grid):
    """Read a grid's items in clockwise spiral order.

    grid: list of rows, each a list of the same length;
        may be empty
    Returns: list, every item once, in spiral order
    """
    # Write your code here
    pass