68. Game of Life
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
grid = [[0, 1, 0],
[0, 1, 0],
[0, 1, 0]][[0, 0, 0], [1, 1, 1], [0, 0, 0]]Example 2
grid = [[1, 1], [1, 1]][[1, 1], [1, 1]]Example 3
grid = [[1]][[0]]Constraints
gridhas 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).
- Write a helper that counts a cell's live neighbours: loop over the rows
r - 1tor + 1and columnsc - 1toc + 1, skip any outside the grid, and leave out the cell itself. - Build a new grid rather than changing the old one, so every count uses the old grid. A comprehension builds it row by row:
[[... for c in range(cols)] for r in range(rows)]. - A cell is alive next time if it has 3 live neighbours, or if it is alive now and has 2.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.