50 XP

68. Game of Life

Intermediate grids simulation

In Conway's Game of Life, each cell of a grid is alive (1) or dead (0). Every cell has up to eight neighbours: the cells above, below, left, right and on the four diagonals. All the cells change at once, by these rules:

  • A live cell with 2 or 3 live neighbours stays alive; with fewer it dies of loneliness, with more of crowding.
  • A dead cell with exactly 3 live neighbours comes to life. Otherwise it stays dead.

Cells off the edge of the grid don't exist: they never count as live neighbours, and the grid doesn't wrap round.

Write a function next_generation(grid) that takes the grid as a list of rows of 0s and 1s and returns a new grid of the same size for the next generation. Every cell is judged on the grid as it was: changing cells in place while still counting would use a mix of old and new.

Example 1

Inputgrid = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
Output[[0, 0, 0], [1, 1, 1], [0, 0, 0]]
ExplanationThe middle stays (2 neighbours), the ends die (1), and the middle row's sides wake (3).

Example 2

Inputgrid = [[1, 1], [1, 1]]
Output[[1, 1], [1, 1]]
ExplanationEach live cell has 3 neighbours: it stays.

Example 3

Inputgrid = [[1]]
Output[[0]]
ExplanationNo neighbours at all: it dies.

Constraints

  • grid has 1 to 10 rows of 1 to 10 cells each, all rows the same length; every cell is 0 or 1.

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

Practises List Comprehensions (lesson 15).

Code
def next_generation(grid):
    """Work out the next generation of the Game of Life.

    grid: list of rows, each a list of 0s and 1s
    Returns: list of rows, the same size, for the next
        generation
    """
    # Write your code here
    pass